用Python找到单词中字母的索引的最佳方法是什么?

huangapple go评论49阅读模式
英文:

What's the best way to find the index of a letter in a word with Python?

问题

我希望我写的单词返回我的列表中对应的数字。

到目前为止,我已经创建了这个列表:

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

单词 = 输入('单词:')

并且这段用于分离每个单独的字母:

list word= []

for i in range(len(word)):
    ListWord.append(word[i])

但我不知道从这里该怎么做。

英文:

I want that the word I write return the correspondent number in my list.

So far I've made the list:

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

word = input('word: ')

And this for separate each individual letter

list word= []

for i in range(len(word)):
    ListWord.append(word[i])

but I don't know were to go from here

答案1

得分: 1

这是解决你问题的另一种方法:

word = input("word :")
output = [ord(x) - ord('a') for x in word]

函数 ord 返回与字符关联的整数值,例如 ord('a') = 97。通过从单词中每个字符的 ord 值中减去 ord('a') 的值,你将得到每个字符相对于 a 的位置。所以 a = 0,b = 1,...

英文:

Here is another solution to your problem:

word = input("word :")
output = [ord(x) - ord('a') for x in word]

The function ord returns the integer value associated to a charachter, e.g. ord('a') = 97. By subtracting the value of ord('a') from the ord of each char in the word you'll get the position of each char relative to the position of a. So a = 0, b = 1, ...

答案2

得分: 0

你可以使用列表上的 index() 函数来完成这个操作。

列表 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
单词 = input('单词: ')

结果 = []
for 字母 in 单词:
    字母编号 = 列表.index(字母) + 1
    结果.append(str(字母编号))

print(结果)

请注意,我将代码中的变量名从英文翻译成中文,以便更容易理解,但代码本身没有改变。

英文:

You can do this by using index() function on list.

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
word = input('word: ')

output = []
for letter in word:
    letter_number = list.index(letter) + 1
    output.append(str(letter_number))

print(output)

答案3

得分: 0

请不要将 list 用作变量名,这可能会覆盖内置的列表。

您还可以使用 List comprehension 结合 enumerate

word = input('word: ')
[(lttr, idx) for idx, lttr in enumerate(lst, 1) for letter in word if letter == lttr]

输入:

word: mouse

输出:

[('e', 5), ('m', 13), ('o', 15), ('s', 19), ('u', 21)]
英文:

Please do not use list as a variable name, it may override the built-in list.

You can also use enumerate with List comprehension.

word = input('word: ')
[(lttr,idx) for idx,lttr in enumerate(lst,1) for letter in word if letter == lttr]

word: mouse
[('e', 5), ('m', 13), ('o', 15), ('s', 19), ('u', 21)]

huangapple
  • 本文由 发表于 2023年5月29日 21:50:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76357928.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定