从修改后的列表中访问列表的元素

时间:2013-05-10 11:06:02

标签: python

说我有一个清单:

[[0, 0], [0, 1], [1, 0], [0, 2], [1, 1], [2, 0], [0, 3], [1, 2], [2, 1], [3, 0]]

我根据满足条件的一些元素,从上面的一个列表中生成了另一个列表,假设值等于三:

[[0, 3], [3, 0]]

但是现在我想从更大的列表中访问一些元素,在对我的第二个列表进行一些修改的基础上,让我们说从第二个列表中只有三个等于三的值减去两个。所以我想在第一个列表中访问这些值,在这里我的第二个列表的情况下取值[0,1]和[1,0]。 我该怎么办?

1 个答案:

答案 0 :(得分:1)

这样的事情:

>>> lis = [[0, 0], [0, 1], [1, 0], [0, 2], [1, 1], [2, 0], [0, 3], [1, 2], [2, 1], [3, 0]]
>>> lis1 = [[0, 3], [3, 0]]
#generate lis2 from lis1 based on a condition
>>> lis2 = [[y if y!=3 else y-2 for y in x] for x in lis1]
>>> lis2
[[0, 1], [1, 0]]
#use sets to improve time complexity
>>> s = set(tuple(x) for x in lis2)

#Now use set intersection  or a list comprehension to get the
#common elements between lis2 and lis1. Note that set only contains unique items 
#so prefer list comprehension if you want all elements from lis that are in lis2 
#as well.

>>> [x for x in lis if tuple(x) in s]
[[0, 1], [1, 0]]
>>> s.intersection(map(tuple,lis))
{(0, 1), (1, 0)}