如何多次显示列表中的项目?

时间:2013-10-17 20:18:12

标签: python

它总是第一次出现.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")

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:2)

all_indexes = [idx for idx, value in enumerate(dlist) if value == y]

答案 2 :(得分:0)

这些方面应该有效:

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

这会在您的示例中提供列表[3, 6, 7] ...