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

2024-04-19 19:01:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: orthein列表indexcountwordpotato
3条回答

沿着这些思路应该可以做到:

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

在您的示例中给出了列表[3, 6, 7]。。。你知道吗

你可以用

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)
all_indexes = [idx for idx, value in enumerate(dlist) if value == y]

相关问题 更多 >