简体   繁体   English

在列表中的项目中查找字符的索引 - Python3

[英]Finding the index of a character in an item in a list - Python3

I'm trying to find the index of a character of an item in a list.我正在尝试查找列表中某个项目的字符的索引。 For example:例如:

list = ['hello','how','are','you']

How would I write some code that returns the "o" from 'hello', or the "r" from 'are', for example?例如,我将如何编写一些从“hello”返回“o”或从“are”返回“r”的代码?

To reference a specific member, list[0][1] could be what you're looking for.要引用特定成员, list[0][1]可能就是您要查找的内容。

>>> list_of_words = ['hello','how','are','you']
>>> list_of_words[0][4]
'o'

If you're trying to find a specific character, you could iterate over your list and then iterate again over each member of the list to see if you've found your character如果您要查找特定角色,您可以遍历您的列表,然后再次遍历列表中的每个成员以查看您是否找到了您的角色

for word in words:
    for letter in word:
        # do comparison here

To find the number of the index, you can wrap your iteration in enumerate() to get a tuple of both the value and its index要查找索引的编号,您可以将迭代包装在enumerate()中以获取值及其索引的元组

for index, word in enumerate(words):
    ...

Also as a note for later, it's better not to name your list list , but something more descriptive, such as list_of_words , as it steps on the class (this means if you declared a list() in the same scope, it will try to reference your variable instead of the builtin)另外作为稍后的说明,最好不要命名您的列表list ,而是更具描述性的名称,例如list_of_words ,因为它踩到 class (这意味着如果您在同一个 scope 中声明了一个list() ,它将尝试引用您的变量而不是内置变量)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM