我正在创建一个程序,用户在其中输入名称列表,然后计算机将其打印出任何已复制的名称。我到目前为止的代码是:
names = []
final = []
enter = raw_input('Enter the name')
while enter != 'exit':
names.append(enter)
enter = raw_input('Enter the name')
for i in names:
for a in (names):
a = i + 1
if a == i:
final.append(i)
print final
到达
时出错a = i + 1
我该如何解决这个问题?
答案 0 :(得分:2)
您可以通过执行此操作找到重复项(代替for
循环)
print set(x for x in names if names.count(x) > 1)
这将返回set
变量中多次出现的names
个值。
names = []
final = []
enter = raw_input('Enter the name')
while enter != 'exit':
names.append(enter)
enter = raw_input('Enter the name')
print(set(x for x in names if names.count(x) > 1))
输出:
Enter the nameAndy
Enter the nameAndy
Enter the nameAndy
Enter the nameBob
Enter the nameGeorge
Enter the nameAndy
Enter the nameBob
Enter the nameexit
set(['Bob', 'Andy'])
Bob
和Andy
不止一次输入。乔治不是,因此没有出现在集合中。
答案 1 :(得分:1)
你不能分配给一个字符串对象,如果你想获得列表中有重复项的字符串你最好使用返回Counter对象的collections.Counter
,那么你可以提取那些计数的名字。不止一个。
from collections import Counter
for name,cnt in Counter(names):
if cnt>1:
print name