简体   繁体   English

按给定字符串查找的列表索引

[英]List index find by given string

I have a list and I have a given string.我有一个列表,我有一个给定的字符串。 The list looks like the following:该列表如下所示:

["hello, whats up?", "my name is...", "goodbye"]

I want to find the index in the list of where the given string is, for example:我想在给定字符串所在的列表中找到索引,例如:

  • If the given string is "whats" I want it to return 0如果给定的字符串是“whats”,我希望它返回 0
  • If the given string is "name" it'll be returning 1如果给定的字符串是“name”,它将返回 1

I tried to use list_name.index(given_string) but it says "whats" is not in the list.我尝试使用list_name.index(given_string)但它说“whats”不在列表中。

That is because whats is not really present in the list.那是因为whats并没有真正出现在列表中。 The list actually has "hello, whats up?"该列表实际上有"hello, whats up?" . . So if you set the value of given_string to be like - given_string = "hello, whats up?"因此,如果您将 given_string 的值设置为 - given_string = "hello, whats up?" , then you will get 0 as index. , 然后你会得到 0 作为索引。 The index method just compares the values, in this case entire string. index 方法只是比较值,在本例中是整个字符串。 It does not check for values within the string.它不检查字符串中的值。

Edit 1: This is how I would do it:编辑 1:这就是我的做法:

list = ["hello, whats up?", "my name is...", "goodbye"]
for index, string in enumerate(list):
     if 'whats' in string:
             print index

You could do something like the follwoing:你可以做类似下面的事情:

l = ["hello, whats up?", "my name is...", "goodbye"]
sub_s = "name"
indx = [i for i, s in enumerate(l) if sub_s in s]
print(indx) # [1]

This is more robust in the case where you have more then 1 index如果您有超过 1 个索引,这会更可靠

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

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