很多时候,我使用字典进行键/值查找。 但是,如果我需要查找多个内容,通常会为同一个对象创建一个for循环。 例如:
def check_cond(key):
return True if key in some_dict else False
some_task = [val for val in vals if check_cond(val)]
有一种比一次循环搜索更好的方法吗?
像some_task = fetch_all_conds(vals)
不确定,我的问题是否有意义?
答案 0 :(得分:5)
首先,您的功能没有意义:
userNum = int(input('How many perfect numbers do you wish to sum? (1-4)'))
while userNum != 1 and userNum != 2 and userNum != 3 and userNum != 4:
userNum = input('You did not enter a number 1-4! Try again!')
if userNum == 1:
print('Sum is 6 = 6')
elif userNum == 2:
print('Sum is 6 + 28 = 34')
elif userNum == 3:
print('Sum is 6 + 28 + 496 = 530')
elif userNum == 4:
print('Sum is 6 + 28 + 496 + 8128 = 8658')
完全相同:def check_cond(key):
return True if key in some_dict else False
现在:key in some_dict
与dict键和val之间的交集相同,因此您的理解力可以修改为:
[val for val in vals if check_cond(val)]
如果[val for val in vals if val in some_dict]
中没有重复的值,则可以:
vals
例如:
list(set(vals).intersect(some_dict.keys()))
您可以使用>>> vals = [1, 2, 3]
>>> d = {1:1, 2:2, 4:4, 5:5}
>>> list(set(vals).intersection(d.keys()))
[1, 2]
,但其概念与理解相同。我们甚至可以将filter
键设置为一组,以加快查找速度:
dict