使用数组数据浏览2个列表

时间:2018-02-06 11:00:04

标签: python arrays list loops

这个让我很头疼,而且我很难找到一个带有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中的下一个数据行等。

5 个答案:

答案 0 :(得分:3)

这是一种方法。它直接脱离了我的头顶,因此可能有更好的方法。

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

结果是一个由短名单中的项目键入的字典,其中的值是长列表中该项目的总计数,而不是具有相同索引的子列表。

答案 1 :(得分:2)

这是一种蛮力的解决方案。我修改了输入数据以使结果更有趣:

{{ datas.post.getContent()|raw }}

答案 2 :(得分:2)

可能的方法

  • 循环遍历short_list
  • 中的每个列表
  • 展平long_list中与当前列表不同索引的每个列表,并将其转换为集合。
  • 创建collections.Counter()以存储展平列表中显示的短列表中每个元素的计数。

<强>演示:

from collections import Counter
from itertools import chain

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]]

for i, short_lst in enumerate(short_list):
    to_check = set(chain.from_iterable(long_list[:i] + long_list[i+1:]))
    print(Counter(x for x in short_lst if x in to_check))

<强>输出:

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

答案 3 :(得分:1)

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))

答案 4 :(得分:0)

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] ]
occ = []
for si in short_list:
    occi = []
    for i, e in enumerate(si):
        count = 0
        for li in long_list:
            for j, e1 in enumerate(li):
                if i == j:
                    continue
                elif e == e1:
                    count += 1
        occi.append(count)
    occ.append(occi)
print occ

这应该有用, 快乐的编码:)