[英]How to pick elements with certain values in list of tuples
I want to pick some elements with certain values in list of tuple
.我想在
tuple
列表中选择一些具有特定值的元素。 Assume I have combinatory list of tuples from verticis = [2,3,4,5] which is res = [(2, 3, 5), (2, 4, 5), (3, 4, 5), (2, 3, 4), (2, 3, 4, 5)]假设我有来自 verticis = [2,3,4,5] 的元组组合列表,即 res = [(2, 3, 5), (2, 4, 5), (3, 4, 5), (2 , 3, 4), (2, 3, 4, 5)]
Then I want to pick all the tuples
that contains key=[2,4,5]
in the res.然后我想在 res 中选择所有包含
key=[2,4,5]
的tuples
。 I used List comprehension我使用了列表理解
but raised with error: too many values to unpack (expected 2)
但引发错误:
too many values to unpack (expected 2)
The output should be: [(2, 4, 5),(2, 3, 4, 5)]
output 应该是:
[(2, 4, 5),(2, 3, 4, 5)]
verticis = [2,3,4,5]
items_to_pick = [2, 4, 5]
i, j = len(items_to_pick), len(verticis)
res1 = [com for sub in range(j) for com in combinations(verticis, sub + 1)]
res2 = [com for sub in range(i - 1) for com in combinations(verticis, sub + 1)]
res = list(set(res1) - set(res2))
c = [value for idx, value in enumerate(res) if idx in items_to_pick]
c=[value for idx, value in res if idx in items_to_pick]
It looks like you are trying to extract the index
and the value
from each item.看起来您正在尝试从每个项目中提取
index
和value
。 In that case, use the enumerate
function: c = [value for idx, value in enumerate(res) if idx in items_to_pick]
.在这种情况下,使用
enumerate
function: c = [value for idx, value in enumerate(res) if idx in items_to_pick]
。
You can find more information at the python docs .您可以在python 文档中找到更多信息。
res= [(2, 3, 5), (2, 4, 5), (3, 4, 5), (2, 3, 4), (2, 3, 4, 5)]
items_to_pick = [2, 4,5]
selected= [tup for tup in res if all(i in tup for i in items_to_pick)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.