【问题标题】:How to pick elements with certain values in list of tuples如何在元组列表中选择具有特定值的元素
【发布时间】:2020-11-29 16:33:48
【问题描述】:

我想在tuple 列表中选择一些具有特定值的元素。假设我有来自 verticis = [2,3,4,5] 的元组组合列表,即 res = [(2, 3, 5), (2, 4, 5), (3, 4, 5), (2 , 3, 4), (2, 3, 4, 5)]

然后我想在 res 中挑选所有包含key=[2,4,5]tuples。我使用了列表理解

但出现错误:too many values to unpack (expected 2)

输出应该是:[(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]

【问题讨论】:

  • 我把问题改得更清楚了。
  • 我的意思是让它更清楚。抱歉,如果您愿意,我可以私下发送。

标签: python list tuples list-comprehension combinations


【解决方案1】:

您似乎正在尝试从每个项目中提取 indexvalue。在这种情况下,请使用enumerate 函数:c = [value for idx, value in enumerate(res) if idx in items_to_pick]

您可以在python docs找到更多信息。

【讨论】:

  • 它没有用。并非所有元组都包含 [2,4,5]。
  • @Aras 在您当前的函数中,看起来您只是在提取索引在items_to_pick 中的res 中的元组。如果您想做您所要求的,请查看@ShashSinha 的回答
【解决方案2】:
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)] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 2016-02-03
    • 2010-11-02
    • 2012-11-30
    • 1970-01-01
    相关资源
    最近更新 更多