简体   繁体   English

如何通过在 python 的列表中仅给出该元素的特定部分来查找列表中元素的索引

[英]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所以,你有两个选择

  • override the equality operator.覆盖相等运算符。 not a good idea in your case, since you have simple strings.在你的情况下不是一个好主意,因为你有简单的字符串。
  • rewrite you loop, using a regular expression使用正则表达式重写你的循环
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.

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