I have a list of list that I want to append a constant value to each sublist of the full list, for instance:
我有一个列表列表,我想在整个列表的每个子列表中附加一个常量值,例如:
_lst = [[1, 2], [3, 4], [5, 6]]
and I want to append 7
to each of the sublist so that _lst
becomes:
我想在每个子列表中附加7,以便_lst变为:
[[1, 2, 7], [3, 4, 7], [5, 6, 7]]
Is there a good way to complete the job (such as using zip
)? Thanks!
有没有一个好方法来完成这项工作(比如使用zip)?谢谢!
3 个解决方案
#1
12
for l in _lst: l.append(7)
#2
5
_lst = [ele + [7] for ele in _lst]
#3
1
>>> tmp = [ i.append(7) for i in _lst ]>>> print _lst[[1, 2, 7], [3, 4, 7], [5, 6, 7]]
#1
12
for l in _lst: l.append(7)
#2
5
_lst = [ele + [7] for ele in _lst]
#3
1
>>> tmp = [ i.append(7) for i in _lst ]>>> print _lst[[1, 2, 7], [3, 4, 7], [5, 6, 7]]