2013-10-17 23 views
0

它總是第一次出現.index()。我希望索引等於列表的位置。例如,This word appears in the places, 0,4。如果用戶輸入了可能是輸出的雞。如何多次顯示列表中的項目?

dlist = ["chicken","potato","python","hammer","chicken","potato","hammer","hammer","potato"] 
x=None 
while x != "": 
    print ("\nPush enter to exit") 
    x = input("\nGive me a word from this list: Chicken, Potato, Python, or Hammer") 
    y = x.lower() 
    if y in dlist: 
     count = dlist.count(y) 
     index = dlist.index(y) 
     print ("\nThis word appears",count,"times.") 
     print ("\nThis word appears in the places",index) 
    elif y=="": 
     print ("\nGood Bye") 
    else: 
     print ("\nInvalid Word or Number") 
+1

究竟是什麼問題?你可以發佈你的預期輸出和你當前的輸出嗎? – dckrooney

回答

3

可以使用

r = [i for i, w in enumerate(dlist) if w == y] 
print ("\nThis word appears",len(r),"times.") 
print ("\nThis word appears in the places", r) 

,而不是沿着這些路線

count = dlist.count(y) 
index = dlist.index(y) 
print ("\nThis word appears",count,"times.") 
print ("\nThis word appears in the places",index) 
2
all_indexes = [idx for idx, value in enumerate(dlist) if value == y] 
0

的東西應該工作:

index_list = [i for i in xrange(len(dlist)) if dlist[i] == "hammer"] 

在你的例子中給出了[3, 6, 7]的列表...

+2

任何時候你使用'xrange(len())'你應該使用'enumerate'。 –

+1

@ g.d.d.c真的......老習慣和所有...... – twalberg

相關問題