2015-10-12 79 views
0

我正在创建一个程序,用户在其中输入名称列表,然后计算机将其打印出任何已复制的名称。我到目前为止的代码是:退出循环时出错

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 

我怎样才能解决这个问题,我得到一个错误?

+1

你认为循环做什么? – Andy

+1

如果你指定'a = i + 1'下面的'if'条件,'如果a == i:',永远不会是真的...... – alfasin

+1

'i'是一个字符串,你不能添加'1'。 –

回答

2

您可以找到做这个(代替你for环路)重复

print set(x for x in names if names.count(x) > 1) 

这将返回值出现在names变量多于一个时间的set


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']) 

BobAndy输入了不止一次。乔治不是,因此没有出现在集合中。

+1

BTW:'set()'结构中的列表理解是不必要的开销,生成器是足够的:'set(如果names.count(x)> 1, – AChampion

1

如果您想要获取列表中具有重复项的字符串,最好使用返回Counter对象的collections.Counter,那么您不能分配给字符串对象,那么可以提取那些count超过一个的名称。

from collections import Counter 

for name,cnt in Counter(names): 
    if cnt>1: 
     print name