追加项目列表的列表中的COM prehension [英] Appending item to lists within a list comprehension
问题描述
我有一个列表,比方说, A = [1,2],[3,4],[5,6]]
I have a list, let's say, a = [[1,2],[3,4],[5,6]]
我要添加字符串'A'
每个项目列表中的 A
。
I want to add the string 'a'
to each item in the list a
.
当我使用:
a = [x.append('a') for x in a]
返回 [无,无,无]
。
但是,如果我用:
a1 = [x.append('a') for x in a]
然后它做一些奇怪的。
then it does something odd.
A
,而不是 A1
是 [1,2,'一' ],[3,4,'一'],[5,6,'一']]
。
我不明白为什么第一个调用返回 [无,无,无]
也不知道为什么对 A $ C第二个变化$ C的>而不是
A1
。
I don't understand why the first call returns [None, None, None]
nor why the second changes on a
instead of a1
.
推荐答案
list.append
变异列表本身并返回无
。名单COM prehensions是用于存储的结果,这是不是你想在这种情况下,如果你想只改变原来的列表中。
list.append
mutates the list itself and returns None
. List comprehensions are for storing the result, which isn't what you want in this case if you want to just change the original lists.
>>> x = [[1, 2], [3, 4], [5, 6]]
>>> for sublist in x:
... sublist.append('a')
...
>>> x
[[1, 2, 'a'], [3, 4, 'a'], [5, 6, 'a']]
这篇关于追加项目列表的列表中的COM prehension的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!