使用数组d遍历2个列表

2024-04-26 07:07:21 发布

您现在位置:Python中文网/ 问答频道 /正文

这个让我头痛,我很难找到一个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] ]

我需要知道短\列表中每行的每个数字在长\列表的每行中出现的次数,当两个列表索引相同时,不需要进行比较,因为它们来自同一个数据集。你知道吗

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


Tags: 数据示例列表for情况数字解决方案次数
3条回答
for L1 in short_list:
  for L2 in long_list:
    if not set(L1).issubset(set(L2)):
      for x in L1:
        print("{} has {} occurrences in {}".format(x, L2.count(x), L2))

这里有一个方法。这是直接从我的头上,所以可能有一个更好的方法来做这件事。你知道吗

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()用于在迭代时提供索引。比较索引以确保相同相对位置的子列表不被比较。你知道吗

结果是一个由短列表中的项组成的字典,其值是长列表中该项的总计数,而不是具有相同索引的子列表。你知道吗

这是一个暴力解决方案。我修改了输入数据,使结果更有趣:

from collections import Counter
from toolz import concat

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], [2, 3, 11, 12, 13] ]

for idx, i in enumerate(short_list):
    long_list_filtered = (x for x in concat(long_list[:idx] + long_list[idx+1:]) if x in set(i)))
    print(idx, Counter(long_list_filtered))

# 0 Counter({2: 2, 3: 2})
# 1 Counter({4: 1, 5: 1, 6: 1})
# 2 Counter()
# 3 Counter({10: 1})

相关问题 更多 >