如何添加值在Python嵌套列表

问题描述 投票:-2回答:2

我有一个列表

list= [['1', '2', '4'], ['1', '48', '2'], ['53', '33', '25', '2', '26', '47']]

到这一点newlist:(第一值到值:“2”)中的每个列表

newlist= [['1', '2'], ['1', '48'],['48', '2'], ['53', '33']['33', '25']['25', '2']]

但下面的代码在所有值运行

[m[i:i+2] for i in range(0, len(list), 1)]
python python-3.x list
2个回答
0
投票

你可以用两个for循环,一个试图通过列表和循环for项目迭代通过内部列表index'2'进行迭代。

注:这是不使用list变量名的好做法。

my_list= [['1', '2', '4'], ['1', '48', '2'], ['53', '33', '25', '2', '26', '47']]
new_list = [[i[j],i[j+1]] for i in my_list for j in range(i.index('2'))]

0
投票

可以通过用本身压缩和解与偏移1对中的每个子表的相邻的项目,然后利用itertools.takewhile输出对直到第一项等于'2'

from itertools import takewhile
l = [['1', '2', '4'], ['1', '48', '2'], ['53', '33', '25', '2', '26', '47']]
[list(t) for s in l for t in takewhile(lambda t: t[0] != '2', zip(s, s[1:]))]

这将返回:

[['1', '2'], ['1', '48'], ['48', '2'], ['53', '33'], ['33', '25'], ['25', '2']]
© www.soinside.com 2019 - 2024. All rights reserved.