我有一个元组列表(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")
有没有“更清洁”的方法来实现这一点
试试这个:
如果我理解正确的话,这就是你想要的
您可以一次构建所有三个列表,然后只保留找到的第一个非空列表
为了清晰起见,这需要一些效率
相关问题 更多 >
编程相关推荐