【问题标题】:Grouping up elements from a list in Python 2.7在 Python 2.7 中对列表中的元素进行分组
【发布时间】:2017-01-11 12:20:48
【问题描述】:

好的,我收到了一个巨大的文本。我用正则表达式提取匹配项(此处省略,因为这无关紧要,我不擅长,所以你看不到我的正则表达式有多丑:))并计算它们。然后,为了可读性,我拆分元素并以我需要的方式打印它们:

import re
f = re.findall(r"(...)", PF)
a = [[y,f.count(y)] for y in set(f)]
(' '.join(map(str, j)) for j in w)
for element in w:
    print element

结果类似于

['202', 1]
['213', 2]
['210', 2]
['211', 2]
['208', 2]
['304', 1]
['107', 2]
['133', 1]
['132', 1]
['131', 2]

我需要对元素进行分组,以便得到类似的输出

A ['133', 1]
  ['132', 1]
  ['131', 2]
B ['202', 1]
  ['213', 2]
C ['304', 1]
  ['107', 2]
  ['210', 2]
  ['211', 2]
  ['208', 2]

注意:

  • 在最终结果中,我需要 5 个组(A、B、C、D、E)
  • 元素可能会有所不同,例如明天可能没有 131 个,但我可能有 232 个属于 A 组,并且元素的数量每天都不同
  • 如果每组中的元素按数字排序,那将是完美的,但不是强制性的。
  • 可能听起来很明显,但无论如何我会说清楚,我确切地知道哪些元素需要放在哪个组中。如果它是任何帮助,则组 A可以包含(102,103),B(104,105,106,201,202,203),C(204,205,206,301,302,303,304),D(107,108,109,110,208,209,210,211,213,305,306,307),E(131,132,13,231,232) Li>。 Li>

脚本需要获取当天出现的结果,将它们与上面的列表进行比较,然后分类到相关组中。

提前致谢!

【问题讨论】:

  • 看起来很像这样:stackoverflow.com/a/39300055/1391444 有什么要从那里编辑的吗?还是我误会了?
  • 据我了解,如果A,B...不在列表中,分组是由什么完成的?
  • 我正在研究 itertools groupby,这可能会奏效,谢谢。如果我无法弄清楚,我会再次发表评论:D 为清晰起见编辑 OP。
  • 谢谢!无论如何groupby() 是我认为可以使用的工具。
  • (' '.join(map(str, j)) for j in w) 应该做什么?您只需创建一个生成器并立即丢弃它。

标签: python arrays list python-2.7 count


【解决方案1】:

一个(可能不是最优雅的)解决方案是定义一个包含映射的字典,然后查找元素所属组的名称。

elements = { "133": "A", "132": "A", 
             "202": "B", 
              ... }

然后可以将元素添加到以组名作为键的新字典中:

groups = {"A":[], "B": [], ...}
for element, count in a:
    group = elements[element]
    groups[group].append( (element, count) )

for group in groups:
    groups[group].sort()                   # sort by element
    for element, count in groups[group]:
        print "%s %s %s" % (group, element, count)

【讨论】:

    【解决方案2】:

    您可以设置将元素映射到组的哈希。然后,您可以将每个数组项从 [element,count] 转换为 (group,element,count)(使用元组使其更易于排序等)。对该数组进行排序,然后使用循环或reduce 将其转换为最终输出。

    mapElementsToGroups = {'131': 'A', '202': 'B', '304': 'C', …}
    
    elementsFoundByGroup = {}
    for (group, element, count) in sorted(
                [(mapElementsToGroups[item[0]], item[1], item[2])
                    for item in a]
            ):
        elementsFoundByGroup[group] = elementsFoundByGroup.get(group, []) + [(element, count)]
    

    您现在有了一个字典,将找到的每个组名映射到该组中的元素列表和计数。快速打印是:

    print [
                group + " " +
                elements.join("\n " + " "*len(group))
                    for (group,elements) in sorted(elementsFoundByGroup.items())
            ].join("\n")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多