【发布时间】: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 万。运行时间很高,我需要减少它。 我阅读了使用综合列表可以帮助减少执行时间的文章。
我的问题
- 如何将此代码转换为综合列表?
- 您是否推荐任何其他方法来减少执行时间?
【问题讨论】:
-
您确定要为“i”设置 5 个匹配项吗?
-
@antimon 是的,这只是一个例子。 For 循环是主要问题
标签: python list runtime bigdata list-comprehension