gpt4 book ai didi

python - 对多个列表重复操作

转载 作者:太空宇宙 更新时间:2023-11-03 18:58:16 25 4
gpt4 key购买 nike

让我们假设以下列表:

totest=[2,4,5,3,6]
l1=[6,8,7,9,4]
l2=[3,12,21,30]
l3=[2,5]

以及以下函数:

def evalitem(x):
...detail....

除非有异常(exception),否则我必须针对 totest 与序列中所有其他列表的交集执行该函数。
总是有以下选项:

test1=set(totest)&set(l1)
try:
for i in test1:
evalitem(i)
except:
return
test2=.....

但是应该有一种更快的Pythonic函数式方法来实现这一点,并且具有更好的性能。
请注意,只有当 test1 没有引发异常时,我们才会评估 test2。

最佳答案

totest = set(totest)

for lst in l1, l2, l3:
for item in totest.intersection(lst):
evalitem(item)

如果你不知道如何处理异常(except: return 不算),则无需使用 try... except at全部。在调用相关函数的代码中处理它。

关于python - 对多个列表重复操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16748885/

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