首页 > 解决方案 > 如何在python中查找列表中的项目索引

问题描述

我是 techy101,我想知道如何在 python 的列表中找到项目的索引,我之前尝试过这个.index函数,但没有给我想要的输出,我也尝试过这个enumerate()函数,再次它没有'没有给出一个好的输出,这是我的代码:

alphabet = list("abcdefghijklmnopqrstuvwxyz")
message = list(input("enter message (only words not numbers):"))
key = int(input("enter key: "))
w = 0
compile_list = []
for eggsample in range(len(message)):
    print(f"thingy: {message[w]}")
    
    print(f"index is {message.index(message[w])}")
    number = message.index(message[w]) + key
    print(number)
    _ = alphabet[number]
    print(_)
    compile_list.append(_)
    w+=1
print("your new message is: ")
print("".join(compile_list))

它给了我这个:

thingy: h
index is 0
2
c
thingy: e
index is 1
3
d
thingy: l
index is 2
4
e
thingy: l
index is 2
4
e
thingy: o
index is 4
6
g

有谁知道如何实际找到该项目的索引?

标签: pythonpython-3.x

解决方案


尝试改进第 8 行的代码如下

print(f "index is {alphabet.index(message[w])}")

如果要检查“字母”列表而不是“消息”列表中的索引,可以使用 alphabet.index(value)。


推荐阅读