gpt4 book ai didi

python - 从元组列表中查找匹配项

转载 作者:行者123 更新时间:2023-12-05 08:38:52 24 4
gpt4 key购买 nike

我有一个元组列表如下。

x = [('b', 'c'),
('c',),
('a', 'c', 'b'),
('b', 'c', 'a', 'd'),
('b', 'c', 'a'),
('a', 'b'),
('a', 'b', 'c', 'd'),
('a', 'c', 'b', 'd'),
('b',),
('c', 'a'),
('a', 'b', 'c'),
('a',)]

我想提供像 ('a') 这样的输入,然后它应该提供像这样的输出,

[('a', 'c', 'b'), ('a', 'b'),('a', 'b', 'c', 'd'),('a', 'c', 'b', 'd'),('a', 'b', 'c')]
#everything starts with a. But not "a".

或者对于 ('a','b') 的输入,它应该给出

的输出
[('a', 'b', 'c', 'd'),('a', 'b', 'c')]
#everything start with ('a','b') but not ('a','b') itself.

我尝试使用但没有成功。

   print(filter(lambda x: ("a","b") in x, x))
>>> <filter object at 0x00000214B3A545F8>

最佳答案

def f(lst, target):
return [t for t in lst if len(t) > len(target) and all(a == b for a, b in zip(t, target))]

这样:

f(x, ('a', 'b'))

返回:

[('a', 'b', 'c', 'd'), ('a', 'b', 'c')]

关于python - 从元组列表中查找匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61277461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com