Python 列出按给定字符串查找的索引
我有一个列表和一个给定的字符串。列表如下所示:Python 列出按给定字符串查找的索引,python,list,Python,List,我有一个列表和一个给定的字符串。列表如下所示: [“你好,怎么了?”,“我的名字是…”,“再见”] 我想在给定字符串所在位置的列表中查找索引,例如: 如果给定的字符串是“whats”,我希望它返回0 如果给定的字符串是“name”,它将返回1 我尝试使用list\u name.index(给定字符串),但它说“what”不在列表中。您可以执行以下操作: l = ["hello, whats up?", "my name is...", "goodbye"] sub_s = "name" in
[“你好,怎么了?”,“我的名字是…”,“再见”]
我想在给定字符串所在位置的列表中查找索引,例如:
- 如果给定的字符串是“whats”,我希望它返回0
- 如果给定的字符串是“name”,它将返回1
我尝试使用
list\u name.index(给定字符串)
,但它说“what”不在列表中。您可以执行以下操作:
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]
如果索引超过1个,这是因为
什么
实际上不存在于列表中,那么这一点更为可靠。这个列表实际上有“你好,怎么了?”。因此,如果您将给定字符串的值设置为-gived\u string=“hello,What up?”
,那么您将得到0作为索引。index方法只是比较值,在本例中是整个字符串。它不检查字符串中的值
编辑1:
我会这样做:
list = ["hello, whats up?", "my name is...", "goodbye"]
for index, string in enumerate(list):
if 'whats' in string:
print index
这回答了你的问题吗?