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

标签 python python-3.x

如何将字符串列表中的值与字符串列表中的另一个值进行比较,如果我确实成功地与列表中的 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/

相关文章:

java - 是否有任何可以与 PHP/Python/其他集成的沙盒脚本引擎?

python - 删除 igraph for Python 中的多条边

python - 如何在 Python 3.x 中使用 dateutil.relativedelta?

python - 简单的 HTML 电子邮件 : Basic CSS styles being stripped

python - 密码重置 Django 1.6

pythonw 3.6.6 sys.stdout 在重新分配时不执行任何操作

python - 如何根据 bool 列值压缩 Pandas 数据框?

python - 在python3中找到一个字符串中有一个表情符号

python - 在 scrapy downolader 中间件中使用正则表达式

python - 如何在 while 循环中使用索引每次查找下一个出现的位置