有没有办法防止列表中的项目重复?

我正在开发一个项目,要求用户将玩家姓名输入到列表中。有什么办法可以防止输入相同的名字吗?


到目前为止我的代码:


#Team 1 naming

        print("Team 1 player input")

        elem = int(input("Amount of players: "))

        for i in range(0, elem):

            Team1_list.append(str(input(f'Enter player number {num_team1} name (In batting order) eg J.Smith: ')))

            num_team1 = num_team1 + 1

        print(Team1_list)

我尝试过一些方法,但似乎都不起作用


婷婷同学_
浏览 109回答 3
3回答

慕虎7371278

如果您希望用户重试该条目,您可以使用如下内容:print("Team 1 player input")elem = int(input("Amount of players: "))for i in range(0, elem):    p = None    while not p or p in Team1_list:        p = input(f'Enter player number {num_team1} name (In batting order) eg J.Smith: ')        if p in Team1_list: print('That player already entered, please retry...')    Team1_list.append(p)    num_team1 = num_team1 + 1print(Team1_list)

湖上湖

使用setwith 集{}no_duplicates = {1, 2, 1, 3, 2}print(no_duplicates){1, 2, 3}

翻阅古今

如果您使用的是 Python 3.6+,您将受益于dict按键记住您的插入顺序。因此,您可以同时受益于list和。set考虑以下:#Team 1 namingprint("Team 1 player input")elem = int(input("Amount of players: "))team = {}while len(team) < elem:&nbsp; &nbsp; num_team1 = len(team)+1&nbsp; &nbsp; name = str(input(f'Enter player number {num_team1} name (In batting order) eg J.Smith: ')))&nbsp; &nbsp; team[name] = 1print(list(team.keys()))如果您再次输入相同的名称,您的num_team1名称将不会增加,并且您的“列表”将忽略该重复的条目(即仅保留第一个条目的原始顺序)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python