[英]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]
注意:
腳本需要獲取當天出現的結果,將它們與上面的列表進行比較,然后對相關組進行排序。
提前致謝!
您可以設置將元素映射到組的哈希。 然后,您可以將每個數組項從[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.