如何删除并显示列表中有重复的字符串?

How to remove and show there were string duplicates in a list?

如果我不断地从用户输入中添加字符串。如何检查将字符串添加到列表后,内容是否已经在其中?

x = 4
y = 9
repeatList = []
abc = str(x)+str(y)
repeatList.append(abc)
x = 3
y = 2
abc = str(x)+str(y)
repeatList.append(abc)
x = 4
y = 9
abc = str(x)+str(y)
repeatList.append(abc)
print(repeatList)

给出输出:

['49', '32', '49']

期望的输出是 ['49','32'] 和一条消息 "You have inputted '49' already."

请注意,在实际代码中,我们不会将变量分配给 int,相反,我们允许玩家输入,如果他们之前已经编写过,那么我们会让他们知道他们输入了相同的输入,并且他们仍然失去了 'move'.

假设您要将变量 x 插入到您的列表中,因此您检查:

if x in lst:
    print ("You have inputted", x, "already.")
else:
    lst.append(x)
x = 4
y = 9
repeatList = []
if str(x)+str(y) not in repeatList:
    repeatList.append(str(x)+str(y))
else:
     print('You have inputted {0} already.'.format(str(x)+str(y)))

x = 3
y = 2
if str(x)+str(y) not in repeatList:
    repeatList.append(str(x)+str(y))
else:
     print('You have inputted {0} already.'.format(str(x)+str(y)))
x = 4
y = 9
if str(x)+str(y) not in repeatList:
    repeatList.append(str(x)+str(y))
else:
     print('You have inputted {0} already.'.format(str(x)+str(y)))
print(repeatList)

输出:

You have inputted 49 already.
['49', '32']

除了@idos 已经说过的:
如果您对插入的顺序不感兴趣并且您添加的对象是 hashable, you could use a set, which has faster performance than lists 时检查元素是否已经在其中。

>>> s = set()
>>> s.add(49)
>>> s
set([49])
>>> s.add(32)
>>> s
set([32, 49])
>>> s.add(49)
>>> s
set([32, 49])
>>> s.add('49')
>>> s
set([32, 49, '49'])