Appending item to lists within a list comprehensio

2020-01-24 09:56发布

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.

7条回答
聊天终结者
2楼-- · 2020-01-24 10:20

You can use list addition within a list comprehension, like the following:

a = [x + ['a'] for x in a] 

This gives the desired result for a. One could make it more efficient in this case by assigning ['a'] to a variable name before the loop, but it depends what you want to do.

查看更多
登录 后发表回答