gpt4 book ai didi

python - 使用数组数据遍历 2 个列表

转载 作者:太空狗 更新时间:2023-10-30 00:47:34 25 4
gpt4 key购买 nike

这个问题让我很头疼,我很难找到带有 for 循环的解决方案。

基本上,我的数据是这样的:

short_list = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]
long_list = [ [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [6, 7, 8, 9, 10], [9, 10, 11, 12, 13] ]

我需要知道 short_list 中每一行的每个数字在 long_list 的每一行中出现了多少次,并且当两个列表索引相同时不需要比较,因为它们来自相同的数据集。

示例:我需要知道 long_list 行 [2, 3, 4, 5, 6],[6, 7, 8, 9, 10] 和 [1, 2, 3] 中每个数字的出现次数[9、10、11、12、13]。然后继续 short_list 中的下一个数据行,等等。

最佳答案

这是一种方法。它就在我的脑海中,所以可能有更好的方法来做到这一点。

from collections import defaultdict

short_list = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]
long_list = [ [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [6, 7, 8, 9, 10], [9, 10, 11, 12, 13] ]

occurrences = defaultdict(int)

for i, sl in enumerate(short_list):
for j, ll in enumerate(long_list):
if i != j:
for n in sl:
occurrences[n] += ll.count(n)

>>> occurrences
defaultdict(<class 'int'>, {1: 0, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 0, 8: 0, 9: 1, 10: 1, 11: 0, 12: 0})

请注意,enumerate() 用于在迭代时提供索引。比较索引以确保不比较相同相对位置的子列表。

结果是以短列表中的项目为键的字典,其值是长列表中该项目的总计数,没有具有相同索引的子列表。

关于python - 使用数组数据遍历 2 个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48641425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com