gpt4 book ai didi

python - 如何比较两个列表中的字符串并创建三分之一的匹配项?

转载 作者:行者123 更新时间:2023-12-05 08:28:56 25 4
gpt4 key购买 nike

如何将字符串列表中的值与字符串列表中的另一个值进行比较,如果我确实成功地与列表中的 2 个进行比较,如果字符串列表中的值,我如何将新值存储在新列表中是火柴吗?

def start_game():
food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
random_food_list = [random.choices (food_list, k = 4)]
player_guess_list = []
correct_guess_list = []

for i in range(1,5):
player_guess = input("food" + str(i) + ":").lower()
if player_guess not in food_list:
print("Invalid foods, Restart Again")
start_game()
else:
player_guess_list.append(player_guess)
print(player_guess_list) # For review
print(random_food_list) # For review

例如:

User input list = [salad, steak, noodles, rice]
randomized list = [salad, rice, salad, rice]
correct_guess_list = [O,X,X,O]

输出

Correct food in correct place: 2
Correct food in wrong place: 2

最佳答案

您可以使用单个 list comprehension 来做您想做的事两个列表中的值 zip一起玩。

food_list = ["salad", "steak", "fries", "rice", "noodles", "fruits"]
#random_food_list = random.choices(food_list, k = 4)
random_food_list = ['salad', 'rice', 'salad', 'rice'] # Hardcode for testing.

correct_guess_list = ['O' if f1.lower() == f2.lower() else 'X'
for f1, f2 in zip(food_list, random_food_list)]

print(correct_guess_list) # -> ['O', 'X', 'X', 'O']

correct_food_in_correct_place = correct_guess_list.count('O')
correct_food_in_wrong_place = correct_guess_list.count('X')

print(f'Correct food in correct place: {correct_food_in_correct_place}') # -> 2
print(f'Correct food in wrong place: {correct_food_in_wrong_place}') # -> 2

关于python - 如何比较两个列表中的字符串并创建三分之一的匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72807116/

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