[英]Finding the index of a character in an item in a list - Python3
我正在嘗試查找列表中某個項目的字符的索引。 例如:
list = ['hello','how','are','you']
例如,我將如何編寫一些從“hello”返回“o”或從“are”返回“r”的代碼?
要引用特定成員, list[0][1]
可能就是您要查找的內容。
>>> list_of_words = ['hello','how','are','you']
>>> list_of_words[0][4]
'o'
如果您要查找特定角色,您可以遍歷您的列表,然后再次遍歷列表中的每個成員以查看您是否找到了您的角色
for word in words:
for letter in word:
# do comparison here
要查找索引的編號,您可以將迭代包裝在enumerate()
中以獲取值及其索引的元組
for index, word in enumerate(words):
...
另外作為稍后的說明,最好不要命名您的列表list
,而是更具描述性的名稱,例如list_of_words
,因為它踩到 class (這意味着如果您在同一個 scope 中聲明了一個list()
,它將嘗試引用您的變量而不是內置變量)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.