如何在python中过滤嵌套列表

时间:2016-04-30 20:09:16

标签: python

我有以下列表:

product date        price
apple   1/1/2011    1.05    
pepper  1/1/2011    0.71 *
apple   1/2/2011    1.04 *
pepper  1/2/2011    0.73
apple   1/3/2011    1.02
pepper  1/3/2011    0.75
apple   1/4/2011    1.07
pepper  1/4/2011    0.76 *
apple   1/6/2011    1.10 *
pepper  1/6/2011    0.79

我想检索以下数据:

[X,Y,[Z]] [X + 1,Y + 1,[Z]] [X + 2,Y + 2,[Z]] [X + 3,Y + 3,[Z] ]

应该得到:

my_list = [
 [0, 0, [21, 24]],
 [0, 1, [2, 13]],
 [0, 3, [1, 15]],
 [0, 4, [1, 6]],
 [0, 6, [11]],
 [0, 7, [1]],
 [1, 0, [3, 4, 10, 17]],
 [1, 1, [1, 15, 19, 24]],
 [1, 2, [1]],
 [1, 3, [5, 6, 18]],
 [1, 4, [15, 24, 25]],
 [1, 5, [10, 22]],
 [1, 6, [16, 30, 31]],
 [2, 0, [7, 20]],
 [2, 1, [5]],
 [2, 3, [11, 14]],
 [2, 4, [5, 10]],
 [2, 5, [15]],
 [2, 6, [6, 10]],
 [2, 7, [12]],
 [3, 0, [11, 18]],
 [3, 2, [2, 22]],
 [3, 5, [8]],
 [3, 6, [15]],
 [3, 7, [5]]
]

其中x是单词中字符的索引,y是行号,z是列号。 你可以看到z可以超过1个选项

[0, 3, [1, 15]],     
[1, 4, [15, 24, 25]],
[2, 5, [15]],      
[3, 6, [15]],       

获取final = [(i,j,) for i,j in my_list if i[0]==j[0] and i[1]==j[1]+1 and i[2]==j[2]]

1 个答案:

答案 0 :(得分:2)

my_list的每个元素都有三个元素,您要将其解压缩为2.这个元素太多了。

>>> i, j = [0, 0]
>>> i, j = [0, 0, 1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>> i, j = [0, 0, [21, 24]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>> i, j, k = [0, 0, [21, 24]]
>>> i
0
>>> j
0
>>> k
[21, 24]