python - 列表理解表达式不显示任何值而不是子列表

标签 python list list-comprehension

我正在学习列表理解,它非常快,但我试图将值插入到子列表中,并且该子列表显示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 返回 Nonenot 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/

相关文章:

Python BeautifulSoup,解析 XML

Python 获取电子邮件

c# - IQueryable、List、IEnumerator 之间的区别?

python - 在 Python 中生成动态列表理解

python - 从另一个文件导入列表

python - 使用字典中的值过滤 Pandas 数据框

list - 从 Kotlin 数字列表中获得一对数字

python - 如何在不复制引用的情况下在 Python 中对列表进行切片?

python - 内部包含 `yield` 的列表理解和生成器理解之间的区别

javascript - 转换 2D 数组理解 |米xn尺寸