Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—只向列表中添加一次内容_Python_List_Python 3.x - Fatal编程技术网

Python—只向列表中添加一次内容

Python—只向列表中添加一次内容,python,list,python-3.x,Python,List,Python 3.x,我的问题是,我只想将字符串“Karte1”添加到列表中一次。但是现在,字符串“Karte1”正在无限次地添加到列表中。。 希望你能帮助我:) 如果需要唯一的值,可以使用集合 但在您的情况下,只需将代码更改为: if "Karte1" not in Deck1: Deck1.append("Karte1") 编辑: 请注意,在while语句中调用函数startgame 2,当定义的函数名为startgame时,if True语句始终为True,因此每次调用startgame()函数时,它

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


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

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

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


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

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

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")

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

来自Python文档

集合模块提供用于构造和操作唯一元素的无序集合的类。常见用途包括成员资格测试、从序列中删除重复项,以及计算集合上的标准数学运算,如交集、并集、差分和对称差分

示例

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]

谢谢,成功了。还有一个问题:有没有办法一次测试多个列表?编辑:是的,只是把它从我的主要来源中删掉,这不是什么大问题^^主要是解决了它post@HealYouDown,您可以使用zip函数循环浏览多个列表<编码>如果len([1表示zip中的项目1、项目2、项目3(li1、li2、l3)如果“Karte1”不在li1中,“Karte1”不在li2中,“Karte1”不在li3中])大于0:…
。感谢您的接受:)