我正在学习列表理解,它非常快,但我试图将值插入到子列表中,并且该子列表显示None
。这是我正在尝试的,
def tester(lst):
print [ x if x%2 else x*100 for x in range(1, 10) ] # It is working
#output: [1, 200, 3, 400, 5, 600, 7, 800, 9]
print [ls.insert(2,"Null") for ls in lst]
#output: [None, None]
lst = [['a','c','d'],['1','2','3']]
tester(lst)
为什么显示[None, None]
?以及为什么它不显示 [['a','c','d', 'Null'],['1','2','3', 'Null']]
最佳答案
list.insert
就地修改列表并返回 None
。
>>> lis = range(5)
>>> repr(lis.insert(2, 'null')) # returns None
'None'
>>> lis # But the list is affected.
[0, 1, 'null', 2, 3, 4]
此处使用简单的 for 循环:
for ls in lst:
ls.insert(2, "Null")
您也可以使用列表理解来完成此操作,但我更喜欢普通循环版本:
>>> lst = [range(5) for _ in range(5)]
>>> [ls for ls in lst if not ls.insert(2, 'null')]
[[0, 1, 'null', 2, 3, 4], [0, 1, 'null', 2, 3, 4], [0, 1, 'null', 2, 3, 4], [0, 1, 'null', 2, 3, 4], [0, 1, 'null', 2, 3, 4]]
这里,当检查 if 条件时,项目将插入到当前列表中,并且 list.insert
返回 None
,not None
始终为True
。
更新:
要根据条件更新列表对象,您需要使用三元表达式:
>>> lst = [['a','c','d'],['1','2','3'], [1, 2, 3, 4]]
>>> [ls if (len(ls) == 3 and not ls.insert(2, 'null')) else ls for ls in lst]
[['a', 'c', 'null', 'd'], ['1', '2', 'null', '3'], [1, 2, 3, 4]]
关于python - 列表理解表达式不显示任何值而不是子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21447870/