我有一本字典已轉換爲列表,因此可以按第一項進行排序。字典中的鍵是一個字符串(數字),該值是一個整數,它保留在列表中。
從字典轉換列表看起來像:按第一項排序嵌套列表 - itemgetter沒有做竅門
[('228055', 1), ('228054', 1), ('228057', 2), ('228056', 1), ('228051', 1), ('228050', 1), ('228053', 1), ('203184', 6), ('228059', 1), ('228058', 1), ('89370', 2), ('89371', 3), ('89372', 2), ('89373', 1), ('89374', 1), ('89375', 1), ('89376', 1), ('89377', 1), ('89378', 1), ('89379', 1),.........]
大約有字典中的24萬項。我想按第一個索引對字典進行排序,但是當我使用itemgetter(0)時,首先按照所有「1」排序列表。將分選的列出看起來像:
[('0', 3), ('1', 3), ('10', 3), ('100', 4), ('1000', 3), ('10000', 1), ('100000', 3), ('100001', 2), ('100002', 3), ('100003', 3), ('100004', 2), ('100005', 2), ('100006', 2), ('100007', 2), ('100008', 2), ('100009', 2), ('10001', 1), ('100010', 3), ('100011', 3), ('100012', 3), ('100013', 2), ('100014', 1), ('100015', 1), ('100016', 1), ('100017', 1), ('100018', 1), ....]
我想列表以由[ '0',3),( '1',3),( '2',整數)進行排序,( '3' ,整數),...('240,000',整數)]
這是我的代碼,我正在閱讀文本文件到字典中,轉換爲列表並使用itemgetter按照嵌套列表中的第一項進行排序。我需要代碼中的字典,因爲我非常依賴它來通過鍵查找值。我只是在所有進程運行後才嘗試對輸出文件的字典進行排序。謝謝你的幫助。
import sys, string, csv, arcpy, os, fileinput, traceback
from arcpy import env
from operator import itemgetter
#Creating a dictionary of FID: LU_Codes from external txt file
text_file = open("H:\SWAT\NC\FID_Whole_Copy.txt", "rb")
#Lines = text_file.readlines()
FID_GC_dict = dict()
reader = csv.reader(text_file, delimiter='\t')
for line in reader:
FID_GC_dict[line[0]] = int(line[1])
text_file.close()
dict_List = [(x, FID_GC_dict[x]) for x in FID_GC_dict.keys()]
dict_List.sort(key=itemgetter(0))
print dict_List
做的更好的方式'text_file =開放(R 「H:\ SWAT \ NC \ FID_Whole_Copy.txt」)' – kev 2012-02-25 18:53:40