Python 检查单词列表中的两个字符串是否相同

Python 检查单词列表中的两个字符串是否相同,python,random,Python,Random,现在我正在做一个类似吃角子老虎机的代码,我遇到了一个障碍 在这篇文章中,你会得到一个包含结果的单词列表。(SlotOption是另一个单词列表) 我试图制作一个片段,比较单词列表中的所有字符串,以检查它们是否相同。有人能帮忙吗?您可以使用set方法检查您的案例中是否有相同的元素 例如: import random slotOption = ['AA', 'BB', 'CC', 'DD', 'EE'] slots = [random.choice(slotOption), random.choi

现在我正在做一个类似吃角子老虎机的代码,我遇到了一个障碍

在这篇文章中,你会得到一个包含结果的单词列表。(SlotOption是另一个单词列表)


我试图制作一个片段,比较单词列表中的所有字符串,以检查它们是否相同。有人能帮忙吗?

您可以使用set方法检查您的案例中是否有相同的元素

例如:

import random

slotOption = ['AA', 'BB', 'CC', 'DD', 'EE']
slots = [random.choice(slotOption), random.choice(slotOption), random.choice(slotOption)]


if len(set(slots)) != 3:
    print("Dupe in list")
您可以在此处使用
set()
,它将只返回列表中唯一的元素。如果集合的元素少于原始列表,则原始列表中存在重复元素

def has_duplicate(l):
    return len(set(l)) < len(l)

has_duplicate([1,2,3,4]) # False
has_duplicate([1,2,3,4,2]) # True
def具有重复(l):
返回len(set(l))
我认为您需要:

def is_winner(l):
    #if len(set(l)) == 2 #if you want to return True on any 2 elements are the same in the list
    if len(set(l)) == 1: #if you want to return True if all elements are the same
        return 'You won!'
    else:
        return 'You lost!'

测试:


请给出一个最小的、可行的、完整的例子,它们的标准是什么?精确匹配?
如果插槽中的“xyz”无效:
是否尝试了
如果len(插槽)==len(设置(插槽))
def is_winner(l):
    #if len(set(l)) == 2 #if you want to return True on any 2 elements are the same in the list
    if len(set(l)) == 1: #if you want to return True if all elements are the same
        return 'You won!'
    else:
        return 'You lost!'
In [11]: is_winner(['7','7','7'])
Out[11]: 'You won!'