簡體   English   中英

在Python 2.7中對列表中的元素進行分組

[英]Grouping up elements from a list in Python 2.7

好的,我收到了一個巨大的文字。 我用正則表達式提取匹配(這里省略,因為它沒關系,我對此不好,所以你看不出我的正則表達式有多丑啊)並計算它們。 然后,為了便於閱讀,我拆分元素並以我需要的方式打印它們:

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,133,231,232)

腳本需要獲取當天出現的結果,將它們與上面的列表進行比較,然后對相關組進行排序。

提前致謝!

您可以設置將元素映射到組的哈希。 然后,您可以將每個數組項從[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")

一個(可能不是最優雅的)解決方案是使用映射定義字典,然后查找該元素所屬的組的名稱。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM