将项目附加到列表理解中的列表 [英] Appending item to lists within a list comprehension

查看:28
本文介绍了将项目附加到列表理解中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,比方说,a = [[1,2],[3,4],[5,6]]

我想将字符串 'a' 添加到列表 a 中的每一项.

当我使用时:

a = [x.append('a') for x in a]

它返回[None,None,None].

但是如果我使用:

a1 = [x.append('a') for x in a]

然后它会做一些奇怪的事情.

a,但不是 a1[[1,2,'a'],[3,4,'a'],[5,6,'a']].

我不明白为什么第一个调用返回 [None, None, None] 也不明白为什么第二个调用在 a 而不是 a1>.

解决方案

list.append 改变列表本身并返回 None.列表推导式用于存储结果,如果您只想更改原始列表,则在这种情况下这不是您想要的.

<预><代码>>>>x = [[1, 2], [3, 4], [5, 6]]>>>对于 x 中的子列表:... sublist.append('a')...>>>X[[1, 2, 'a'], [3, 4, 'a'], [5, 6, 'a']]

I have a list, let's say, a = [[1,2],[3,4],[5,6]]

I want to add the string 'a' to each item in the list a.

When I use:

a = [x.append('a') for x in a] 

it returns [None,None,None].

But if I use:

a1 = [x.append('a') for x in a]

then it does something odd.

a, but not a1 is [[1,2,'a'],[3,4,'a'],[5,6,'a']].

I don't understand why the first call returns [None, None, None] nor why the second changes on a instead of a1.

解决方案

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']]

这篇关于将项目附加到列表理解中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆