我有一个看起来像这样的字典:
BACKPACK = {'granola bar': 1, 'cooked meat': 1, 'raw meat': 1, 'dried foods': 1}
我想要做的是检查列表中是否有一个或多个元素出现在该字典中,如果是,我想转到下一个方法,如果不是,我想做其他的事情。
BACKPACK = {'granola bar': 1, 'cooked meat': 1, 'raw meat': 1, 'dried foods': 1}
HEALTH = 25
def rest():
print formatter()
foods = ['granola bars', 'cooked meat', 'dried foods']
for food in foods:
if food in BACKPACK:
eat_food(BACKPACK, HEALTH)
break
else:
print "You don't have any food in your pack." \
" You decide to go hunting."
# go_hunting()
def eat_food(food, health):
print food
print health
如果dict中的键与功能中的列表一致,我想要打印出可供吃的食物列表。
例如,如果我有这个:
BACKPACK = {'cooked meat': 1, 'raw meat': 1}
foods = ['granola bars', 'cooked meat', 'dried foods', 'raw meat']
这应输出:
1. cooked meat
2. raw meat
我为这种困惑道歉
答案 0 :(得分:1)
编辑:你的循环是错误的使用这个
BACKPACK ={'cooked meat': 1, 'raw meat': 1}
HEALTH = 25
def rest():
# print formatter()
foods = ['granola bars', 'cooked meat', 'dried foods', 'raw meat']
for food in BACKPACK:
if food in foods:
eat_food(food,HEALTH)
else:
print "You don't have any food in your pack." \
" You decide to go hunting."
# go_hunting()
def eat_food(food,health):
#get rid of food
#add health
print food
rest()
答案 1 :(得分:1)
这你需要什么?它应该现在正常工作:
BACKPACK = {'raw meat': 1, 'raw meat': 1, 'granola bar': 1, 'dried foods': 1, 'cooked meat': 1}
HEALTH = 25
def rest():
foods = ['granola bar', 'cooked meat', 'dried foods']
back = {}
for x in foods:
for y in BACKPACK:
if y in foods:
back[y] = 1
for key, value in back.items():
print("1. " + str(key))
def eat_food(food, health):
print(food)
print(health)
rest()
答案 2 :(得分:0)
如果您只想获取列表中的所有密钥,则应使用集:
intersection = set(mylist) & set(mydict.keys())
如果没有,交集将是一个带有假bool的空集,否则它将具有真正的bool。要检查是否有这样的元素,你可以写下:
if intersection:
do_sth
else:
do_sth_else