[英]how to find the index of an element in a list by giving only a specific part of that element in a list in python
a=["cat on the wall" ,"dog on the table","tea in the cup"]
b= "dog"
for i in a:
if b in i:
print(a.index(i))
The output prints the index of the element where is "dog" is present output 打印存在“dog”的元素的索引
can this be done in using any inbuilt function, variable b contains only a part of the element in the list.这可以使用任何内置的 function 来完成吗,变量 b 仅包含列表中元素的一部分。
Looks like you need enumerate
看起来你需要
enumerate
Ex:前任:
a=["cat on the wall" ,"dog on the table","tea in the cup"]
b= "dog"
for idx, v in enumerate(a):
if b in v:
print(idx) #-->1
a=["cat on the wall" ,"dog on the table","tea in the cup"]
b= "dog"
for z in a:
if b in z:
print(a.index(z))
There's no direct way to do it.没有直接的方法可以做到这一点。 Other functions (eg.
sorted
) accept a key that they use to compare elements.其他函数(例如
sorted
)接受他们用来比较元素的键。 But index
depends on equality.但是
index
取决于相等性。 So, you have two choices所以,你有两个选择
import re
for word in a:
position = re.search(b, word)
if position is not None:
start_index = position.span()[0]
print(start_index)
As blue_note mentioned there is no direct way for this.正如 blue_note 提到的,没有直接的方法。 You can simplify usingList Comprehension .
您可以使用List Comprehension进行简化。 Like,
喜欢,
a = ["cat on the wall", "dog on the table", "tea in the cup"]
b = "dog"
print ([idx for idx, itm in enumerate(a) if b in itm])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.