亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過python中的第一個字符有效地對巨大列表中的元素進行分組

如何通過python中的第一個字符有效地對巨大列表中的元素進行分組

夢里花落0921 2021-10-05 16:27:32
import jsonfrom itertools import groupby#Load datawith open('input.txt', 'r') as f:    concepts = []    for concept in f:        concepts.append(concept.strip())print(len(concepts))concepts_list = [list(g) for k, g in groupby(concepts, key=lambda x: x[0])]concepts_dict = {}for item in concepts_list:    concepts_dict[item[0][0]] = itemwith open("concepts_preprocessed_dictionary.txt", "w") as fw:    fw.write(json.dumps(concepts_dict))但是,我想知道為什么當列表中有大量概念(大約 13,000,000 個概念)時這段代碼不起作用。令人驚訝的是,程序在幾秒鐘內執行,當我檢查字典時,它包含錯誤的結果(換句話說,字典文件的大小只有 1KB,每個分組列表主要包含一兩個元素)。不幸的是,我無法分享我的概念清單,因為它違反了一些隱私問題。但是我在以下 github 頁面中發現了一個很長的單詞列表:https : //raw.githubusercontent.com/dwyl/english-words/master/words.txt但是,與上述數據集不同,我當前的數據集僅按第一個字符按字母順序排列(即如下)我的數據集:只有第一個字母是m,但其余單詞沒有按順序排列方法機器學習麥克風我提到的數據集:根據字符很好地排序機器學習方法麥克風如果需要任何進一步的細節,請告訴我。
查看完整描述

1 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

你真的不需要使用groupby來做到這一點。


考慮您的鏈接示例:


list1=['hello','hope','hate','hack','bit','basket','code','come','chess']

您可以創建使用本機 Python 字典描述的組:


groups={}

for word in list1:

    groups.setdefault(word[0],[]).append(word)


>>> groups

{'h': ['hello', 'hope', 'hate', 'hack'], 'b': ['bit', 'basket'], 'c': ['code', 'come', 'chess']}

或者,defaultdict如果您愿意:


from collections import defaultdict 

groups=defaultdict(list)    

for word in list1:

    groups[word[0]].append(word)


>>> groups

defaultdict(<class 'list'>, {'h': ['hello', 'hope', 'hate', 'hack'], 'b': ['bit', 'basket'], 'c': ['code', 'come', 'chess']})

這兩種方法都適用于完全未排序的數據,并根據第一個字母收集單詞。然后,如果需要,您可以自由使用該 dict 的值來制作列表列表:


>>> sorted(groups.values(), key=lambda s: s[0])

[['bit', 'basket'], ['code', 'come', 'chess'], ['hello', 'hope', 'hate', 'hack']]

現在,如果您出于某種原因仍想使用groupby,您可能會執行以下操作:


groups={}

for k,v in groupby(list1, key=lambda s: s[0]):

    groups.setdefault(k,[]).extend(v)


查看完整回答
反對 回復 2021-10-05
  • 1 回答
  • 0 關注
  • 228 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號