在特定元素出现之前计算列表中的元素数
Count number of elements in list prior to occurrence of specific element
假设我们有一个单词列表存储在这样的列表中:
list_of_words = ["this", "is", "a", "text","for", "demonstration"]
另外,我有一个选词列表:
selected_words = ["hello", "text", "demonstration"]
我想计算 list_of_words 中出现在 selected_words 中与 list_of_words 中的词相匹配的词之前的词数(元素,如果你愿意的话)。 =12=]
即selected_word 中匹配的第一个单词是 "text",并且在 list_of_words 中该单词之前有 3 个单词。匹配的第二个词是 "demonstration",它前面有 5 个词。所以输出应该是 [3, 5]。
最有效的计算方法是什么?我似乎在 python 中找不到其他人问过这个问题。
使用enumerate
and a conditional list comprehension:
[i for i, word in enumerate(list_of_words) if word in selected_words]
# [3, 5]
如果涉及的列表非常大,您应该考虑事先将 selected_words
转换为 set
以改进包含检查:
selected_words = set(selected_words)
[i for i, word in enumerate(list_of_words) if word in selected_words]
# [3, 5]
假设我们有一个单词列表存储在这样的列表中:
list_of_words = ["this", "is", "a", "text","for", "demonstration"]
另外,我有一个选词列表:
selected_words = ["hello", "text", "demonstration"]
我想计算 list_of_words 中出现在 selected_words 中与 list_of_words 中的词相匹配的词之前的词数(元素,如果你愿意的话)。 =12=]
即selected_word 中匹配的第一个单词是 "text",并且在 list_of_words 中该单词之前有 3 个单词。匹配的第二个词是 "demonstration",它前面有 5 个词。所以输出应该是 [3, 5]。
最有效的计算方法是什么?我似乎在 python 中找不到其他人问过这个问题。
使用enumerate
and a conditional list comprehension:
[i for i, word in enumerate(list_of_words) if word in selected_words]
# [3, 5]
如果涉及的列表非常大,您应该考虑事先将 selected_words
转换为 set
以改进包含检查:
selected_words = set(selected_words)
[i for i, word in enumerate(list_of_words) if word in selected_words]
# [3, 5]