對於多個數組的合併及按序排列

trans_out_res.txt
[67545 69287 82972 70845 80996]
[142522  90580  97826  97562  72554]
[302981 254754 308544 273743 134552]
[139220  75252  72992  12517  90535]
[ 31490 299477 299478 233707 316110]



list_res = []
with open("../TransH/trans_out_res.txt", 'r', encoding='utf-8') as fo:
    sentence = fo.readline()
    while sentence:
        sentence = sentence.replace("\n", "")
        sentence = sentence.replace("]", "")
        sentence = sentence.replace("[", "")
        tmp = sentence.split()
        for num in tmp:
            list_res.append(int(num))
        sentence = fo.readline()

print(list_res)

排序:

# 將數字和對應重複次數作爲key,value放入字典
a = {}
for i in list_res:
    if list_res.count(i) >= 1:
        a[i] = list_res.count(i)
        # 對字典value(重複次數)降序排序,以列表形式返回
a = sorted(a.items(), key=lambda item: item[1], reverse=True)
# [(5, 6), (1, 3), (2, 2), (4, 2)]
num = []
# 獲取列表中每個元組中的第一個值,即數組中的數字(此時已是按重複次數降序)
for item in a:
    num.append(item[0])
print(num)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章