繁体   English   中英

从Python中的元组列表中获取配对元素

[英]Get paired element from a list of tuples in Python

假设我有一个像这样的元组列表(没有任何数字的重复):

lst = [(4, 1), (3, 8), (2, 9), (5, 6), (7, 0)]

我知道元素值a ,我想找到配对值b
但是,我不知道a是元组的第一个还是第二个元素。

有没有办法轻松干净地找到它?

我试过这个:

a = 8
pair = next(t for t in lst if t[0] == a or t[1] == a)
b = pair[0] if pair[1] == a else pair[1]

这看起来不太好......有更聪明的东西存在吗?

在O(n)中存在一个非常酷的双向映射技巧。 首先,你必须压扁你的清单:

l = [1, 4, 3, 8, 9, 2, 5, 6, 7, 0]

然后找到一个相关的元素非常简单:

a = 8
b = l[l.index(a) ^ 1]

这是有效的,因为如果数字为偶数,则带1的数字加1,如果数字为奇数则加1。

使用列表理解。

>>> lst = [(1, 4), (3, 8), (9, 2), (5, 6), (7, 0)]
>>> next(y if 8 == x else x for x,y in lst if 8 in (x,y))
3
>>> next(x[1] if 8 == x[0] else x[0] for x in lst if 8 in x)
3

关于什么:

>>> lst = [(1, 4), (3, 8), (9, 2), (5, 6), (7, 0)]

>>> a = 8
>>> next([i[i.index(a) ^ 1] for i in lst if a in i])
3

>>> a = 4
>>> next(i[i.index(a) ^ 1] for i in lst if a in i)
1

>>> a = 7
>>> next(i[i.index(a) ^ 1] for i in lst if a in i)
0

如果您的lst未更改,并且您正在执行多次查找,则可以在线性时间( O(n) )中构建查找表,以便在常量时间( O(1) )中获得答案,或者在平均情况下接近它。

如果你的lst包含连续的整数,并且其中一个是0 ,你可以使用list作为查找表来获得O(1)查找:

lookup = [None] * len(lst) * 2
for x, y in lst:
     lookup[x] = y
     lookup[y] = x

print(lookup[4]) # 1    

如果没有,你可以改用dict (更慢的查找,更多的可能性)。 您可以随时轻松切换到它,因为它可以与上面的列表类似地构建:

lookup = {}
for x, y in lst:
    lookup[x] = y
    lookup[y] = x

它也可以以功能方式构建:

from itertools import chain
flatten = chain.from_iterable
dct = dict(flatten(((x, y), (y, x)) for x, y in lst))

你可以这样做

lst = [(4, 1), (3, 8), (2, 9), (5, 6), (7, 0)]

#number to be searched
num = 3

x = list(filter(lambda y: num in y, lst))

if x:
    x = list(x[0])
    x.remove(num)
    print(x)
else:
    print('Not Found')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM