基于子字符串打印条件索引值



我觉得这很简单。我有一个包含字符串的列表,如果它包含某个单词(triggerword(,我想打印索引。我可以让它拉取索引,但在列表中打印该索引的实际值时遇到了问题。

list = [' test', ' tests triggerword', ' test3', ' 12345']
x = [list.index(i) for i in list if 'triggerword' in i]
print(x)
[1]

我想打印tests triggerword

尝试:

my_list = [' test', ' tests triggerword', ' test3', 'triggerword', ' 12345']
x = [[my_list.index(i), i] for i in my_list if 'triggerword' in i]
print(x)
>>> [[1, ' tests triggerword'], [3, 'triggerword']]

BTW,list应该保留为python函数。将其用作变量不是一个好主意。所以,我会把它改成my_list或类似的。否则,您可能会遇到以下错误:

print(list(list))
>>> TypeError: 'list' object is not callable

您可以在遍历数组时使用enumerate来获取索引,然后返回索引和实际元素的元组。见下文:

>>> L = [' test', ' tests triggerword', ' test3', ' 12345']
>>> [(i, x) for i, x in enumerate(L) if 'triggerword' in x]
[(1, ' tests triggerword')]

最新更新