如果没有嵌套的ifs,如何根据自定义首选项生成具有公共第二个元素的非空元组列表?

2024-05-15 21:01:33 发布

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

我有一个元组列表(a,b),其中b等于1、2或3。 我想列一个a的whereb == 2列表。如果这个列表是空的,我想列出所有a的whereb == 1。如果它也是空的,那么我想列出所有a的b == 3

现在我正在使用嵌套if来实现这一点:

sizeTwo = [tup[0] for tup in tupleList if tup[1] == 2]
if sizeTwo:
        targetList = sizeTwo
else:
        sizeOne = [tup[0] for tup in tupleList if tup[1] == 1]
        if sizeOne:
                targetList = sizeOne
        else:
                sizeThree = [tup[0] for tup in tupleList if tup[1] == 3]
                if sizeThree: 
                        targetList = sizeThree
                else: 
                        print(f"Error: no matching items in tupleList")

有没有“更清洁”的方法来实现这一点


Tags: in列表foriferrorelse元组print
2条回答

试试这个:

tuplist=[(2,3), (1,2), (5,1), (4,2)]

blist=[2,1,3]

newlist=[]

for b in blist:
   for tup in tuplist:
      if tup[1] == b:
         newlist.append(tup)
   if newlist:
      break

print(newlist)

如果我理解正确的话,这就是你想要的

您可以一次构建所有三个列表,然后只保留找到的第一个非空列表

from collections import defaultdict


groups = defaultdict(list)
for a, b in tupleList:
    groups[b].append(a)

targetList = groups[2] or groups[1] or groups[3]
del groups

if not targetList:
    print("error")

为了清晰起见,这需要一些效率

相关问题 更多 >