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

2024-09-29 19:23:25 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我正在做一个类似老虎机的代码,我遇到了一个障碍。你知道吗

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

slots = [random.choice(slotOption), random.choice(slotOption), random.choice(slotOption)]

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


Tags: 字符串代码列表random单词障碍choiceslots
3条回答

您可以使用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")

我想你需要:

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!'

您可以在这里使用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

相关问题 更多 >

    热门问题