【问题标题】:Reduce runtime of for loop using comprehensive list使用综合列表减少 for 循环的运行时间
【发布时间】:2021-02-28 06:21:54
【问题描述】:

我有两个列表:

List1 ['i', 'me', 'my', 'myself', 'we']
List2 =  ['i am legend', 'its me time', 'my book is red ', 'i told myself', 'we are thinking about we']

我想检查 List1 的元素在 List2 中出现的次数。

count = 0
occurance = []
for row in range(len(List1 )):
   for item in range(len(List2 )):
       if List1 [row] in List2 [item]:
           count += 1 
   occurance.append(count)
   count = 0
result = list(zip(occurance,List1))

此代码正在运行,结果是 [(5, '我'), (1, '我'), (2, '我的'), (1, '我自己'), (1, '我们')]

问题:

现实世界中 List2 的大小为 8200 万。运行时间很高,我需要减少它。 我阅读了使用综合列表可以帮助减少执行时间的文章。

我的问题

  1. 如何将此代码转换为综合列表
  2. 您是否推荐任何其他方法来减少执行时间?

【问题讨论】:

  • 您确定要为“i”设置 5 个匹配项吗?
  • @antimon 是的,这只是一个例子。 For 循环是主要问题

标签: python list runtime bigdata list-comprehension


【解决方案1】:

我会使用一本综合词典,但我无法让它完全发挥作用。它想:

x = {k:[List2.count(l)] for l in List2 for k in List1}

从这一点开始真的很容易移动到元组列表。

y = [(k, v) for k, v in x.items()]

【讨论】:

  • 没有if语句
猜你喜欢
  • 2019-10-07
  • 2016-03-12
  • 2018-03-27
  • 2016-10-13
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 1970-01-01
  • 2021-11-03
相关资源
最近更新 更多