Python只在

2024-10-01 07:48:23 发布

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

我的问题是我只想将字符串“Karte1”添加到列表中一次。但是现在,字符串“Karte1”正在无限次地添加到列表中。。 希望你能帮助我:)

import random

Deck1 = []

def startgame():
    try:
        "Karte1" not in Deck1
        if True:
            Deck1.append("Karte1")
        if False:
            pass
    except:
        pass


while True:
    startgame()
    print(Deck1)

Tags: 字符串inimporttrue列表ifdefnot
3条回答

if True语句始终为True,因此每次调用startgame()函数时,它都会将其添加到Deck

你可能想做的是:

if "Karte1" not in Deck1:
     Deck1.append("Karte1")

可以使用集合数据结构而不是列表。 默认情况下,集合包含唯一值。在

来自Python Docs

https://docs.python.org/2/library/sets.html

The sets module provides classes for constructing and manipulating unordered collections of unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference.

示例

my_set = set([1,2,3,2])
print(my_set)    # prints [1,2,3]

my_set.add(4)
print(my_set)    # prints [1,2,3,4]

my_set.add(3)
print(my_set)    # prints [1,2,3,4]

如果需要唯一值,可以使用集合。在

但在您的情况下,只需将代码更改为:

if "Karte1" not in Deck1:
    Deck1.append("Karte1")

编辑:

注意,在while语句中,当定义的函数名为startgame时,调用函数startgame2

相关问题 更多 >