[英]Retrieve indices of letters in a string for python
I have a string: "Bob's tank has a big boom!" 我有一句话:“鲍勃的坦克轰隆隆!”
I want to use filter to find the indices of where letters of the alphabet appear in the string to save their placement to a list. 我想使用过滤器来查找字母在字符串中出现的位置的索引,以将其位置保存到列表中。
import string
alphabet = string.ascii_lowercase
str_ = "Bob's tank has a big boom!"
list_index = list(filter(lambda x: x in alphabet, str_))
Currently it just collects all the letters, but i'd like to know their index in the object str_ . 当前它只收集所有字母,但是我想知道它们在对象str_中的索引。
Edit for more clarity 编辑更清晰
Output should be: 输出应为:
[0,1,2,4,6,7...]
[B,o,b,s,t,a...]
List comprehension with enumerate
: 列表理解与
enumerate
:
[i for i, v in enumerate(str_) if v in alphabet]
i
is the index, v
is the value at corresponding index i
, while enumerate
-ing over the input string i
是索引, v
是对应索引i
的值,同时对输入字符串进行enumerate
if v in alphabet
does the membership test; if v in alphabet
隶属度测试; if found, the index is saved 如果找到,则保存索引
Example: 例:
In [58]: import string
...: alphabet = string.ascii_lowercase
...:
...: str_ = "Bob's tank has a big boom!"
...:
In [59]: [i for i, v in enumerate(str_) if v in alphabet]
Out[59]: [1, 2, 4, 6, 7, 8, 9, 11, 12, 13, 15, 17, 18, 19, 21, 22, 23, 24]
This gives each permitted letter and respective position as a list of tuples: 这给出了每个允许的字母和相应的位置作为元组列表:
import string
alphabet = string.ascii_lowercase
string = "Bob's tank has a big boom!"
[(j, i) for i, j in enumerate(string) if j in alphabet]
# [('o', 1), ('b', 2), ('s', 4), ('t', 6), ('a', 7), ('n', 8),
# ('k', 9), ('h', 11), ('a', 12), ('s', 13), ('a', 15), ('b', 17),
# ('i', 18), ('g', 19), ('b', 21), ('o', 22), ('o', 23), ('m', 24)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.