0

它总是给我它第一次出现的时候.index()。我希望索引等于列表的位置。例如,This word appears in the places, 0,4。如果用户输入了 chicken,那将是输出。

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")
4

3 回答 3

3

you can use

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)

instead of

count = dlist.count(y)
index = dlist.index(y)
print ("\nThis word appears",count,"times.")
print ("\nThis word appears in the places",index)
于 2013-10-17T20:25:08.960 回答
2
all_indexes = [idx for idx, value in enumerate(dlist) if value == y]
于 2013-10-17T20:23:50.350 回答
0

Something along these lines should work:

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

That gives the list [3, 6, 7] in your example...

于 2013-10-17T20:25:54.870 回答