从修改的lis访问列表的元素

2024-03-28 17:12:03 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个清单:

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

我已经从上面的列表中得到了另一个列表,基于一些元素满足一个条件,假设值等于3:

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

但是现在我想访问更大列表中的一些元素,基于对第二个列表的一些修改,比如说从第二个列表中等于3的值中减去2。所以我想访问第一个列表中的那些值,取[0,1]和[1,0]作为第二个列表的例子。 我该怎么做?你知道吗


Tags: 元素列表条件例子
1条回答
网友
1楼 · 发布于 2024-03-28 17:12:03

像这样:

>>> 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)}

相关问题 更多 >