我有一个挑战问题需要解决,这是数据的样子,
data = [{'Clay':[x for x in range(2, 3)]},
{'George':[x for x in range(7)]},
{'Buddy':[x for x in range(5, 8)]},
{'Mark':[x for x in range(7, 11)]},
{'John':[x for x in range(1, 10)]}]
挑战问题是在数据中找到一个值,比如"Buddy"并进一步索引一个数字/值比如6,这是我到目前为止想到的但我在这里卡住了-
data = [{'Clay':[x for x in range(2, 3)]},
{'George':[x for x in range(7)]},
{'Buddy':[x for x in range(5, 8)]},
{'Mark':[x for x in range(7, 11)]},
{'John':[x for x in range(1, 10)]}]
def find_usr(usr, val):
if usr in data:
print("True")
else:
print("False")
find_usr(usr="Buddy", val=6)
它返回False
我不确定这里出了什么问题,我在一个主题上做了一些搜索,但找不到可能的解决方案。
欢迎任何进一步的调试细节!
如果我理解你问的是正确的,我希望这段代码可以帮助:
def find_usr(usr, val):
for dictionary in data:
# Checking each dictionary in the list
if usr in dictionary.keys():
# Only if the user in the current dictionary
if val in dictionary[usr]:
# If the value in the list of the user
return True
# If the value is not in the list of the user
break # We can stop the loop becuase we have found the user
return False
顺便说一下,如果您使用的是一个只有一个键和一个值的字典列表,那么使用字典而不是列表会更好:
data = {'Clay':[x for x in range(2, 3)],
'George':[x for x in range(7)],
'Buddy':[x for x in range(5, 8)],
'Mark':[x for x in range(7, 11)],
'John':[x for x in range(1, 10)]}
所以代码会更有效率:
def find_usr(usr, val):
if usr in data.keys():
# Only if the user in the current dictionary
if val in data[usr]:
# If the value in the list of the user
return True
# If the value is not in the list of the user
break # We can stop the loop becuase we have found the user
return False