[英]Appending item to all sublist of a list in Python
Here are my datasets:这是我的数据集:
R = [["yyy", "3"],["www", "4"],["eee","3"],["zzz", "2"]]
I am trying to append one item ('-1') to all sublists of a list (R) to get a new list (new_R), and keep R unchanged:我正在尝试将 append 一项('-1')添加到列表(R)的所有子列表中以获取新列表(new_R),并保持 R 不变:
print(new_R)
output:
[['yyy', '3', '-1'],
['www', '4', '-1'],
['eee', '3', '-1'],
['zzz', '2', '-1']]
print(R)
output:
[["yyy", "3"],["www", "4"],["eee","3"],["zzz", "2"]]
I tried:我试过了:
new_R = [x.append('-1') for x in R]
and和
new_R = list(map(lambda x: x.append('-1'), R))
However, the results of R and new_R are not expected:但是,R 和 new_R 的结果不是预期的:
print(new_R)
output:
[None, None, None, None]
print(R)
output:
[['yyy', '3', '-1'],
['www', '4', '-1'],
['eee', '3', '-1'],
['zzz', '2', '-1']]
Looking for explanation and solution!寻求解释和解决方案! Thanks!谢谢!
append
operates in place and returns None
, so you don't want that (it's why your solutions create lots of None
s in the new list
while modifying the original list
). append
运行并返回None
,因此您不希望这样(这就是为什么您的解决方案在修改原始list
时在新list
中创建大量None
的原因)。 Simplest solution is just list
concatenation, eg:最简单的解决方案就是list
连接,例如:
new_R = [x + ['-1'] for x in R]
or (with newer syntax for 3.5 and higher , and potentially fewer temporaries) construct a new list
by unpacking the old one plus an extra value:或(对于 3.5 和更高版本的新语法,以及可能更少的临时文件)通过解包旧列表加上一个额外的值来构造一个新list
:
new_R = [[*x, '-1'] for x in R]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.