【问题标题】:Count number of elements in list prior to occurrence of specific element在特定元素出现之前计算列表中的元素数
【发布时间】:2018-09-14 07:12:24
【问题描述】:

假设我们有一个存储在这样一个列表中的单词列表:

list_of_words = ["this", "is", "a", "text","for", "demonstration"]

此外,我有一个选定单词的列表:

selected_words = ["hello", "text", "demonstration"]

我想计算在 selected_words 中与 list_of_words 中的单词匹配的单词之前出现在 list_of_words 中的单词(如果您愿意,可以是元素)的数量。

即selected_word 中匹配的第一个单词是“text”,并且在 list_of_words 中该单词之前有 3 个单词。匹配的第二个单词是“demonstration”,前面有 5 个单词。所以输出应该是[3, 5]。

计算这个最有效的方法是什么?我似乎找不到其他人在 python 中问过这个问题。

【问题讨论】:

  • 对于[3, 5],您无法确定 3 和 5 的来源。你确定这是你理想的输出吗? [None, 3, 5] 之类的东西会更好 imo。
  • 到目前为止您尝试过任何尝试/代码吗?
  • [list_of_words.index(word) for word in selected_words if word in list_of_words]

标签: python list text count element


【解决方案1】:

使用enumerate 和条件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]

【讨论】:

  • 太好了,非常感谢!上面 Ev.Kounis 的一个很好的输入:如果单词没有匹配项,有没有办法返回 NONE。所以输出将改为 [NONE, 3, 5]。
  • @JonathanMarin 如果其中一个词出现两次,你只想要第一次出现吗?
  • 单词出现两次就好了:-)
  • @JonathanMarin 但是你希望你的输出是什么样的呢? :) 有两次出现的数字还是第一次出现的数字?
  • 来自documentation: list.index(x): Return the index in the list of the first item whose value is x. It is an error if there is no such item.
猜你喜欢
  • 2017-07-11
  • 1970-01-01
  • 2015-08-22
  • 2020-06-09
  • 2011-08-10
  • 2021-06-13
  • 1970-01-01
  • 2017-04-03
相关资源
最近更新 更多