按第一项排序嵌套列表——itemgetter不执行tri

2024-09-29 21:45:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,我已经把它转换成一个列表,这样我就可以按第一项排序了。字典中的键是一个字符串(数字),值是一个整数,它保存在列表中。
字典转换的列表如下:

[('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',integer),('3',integer),…('240000',integer)排序

这是我的代码,在这里我将文本文件读入字典,转换成列表,并使用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

Tags: textfromimport列表字典排序lineinteger
2条回答

那是因为它们是弦。

key=lambda x: int(x[0])

更改键以将字符串转换为int将有助于您,这里还有一些其他排序提示。

from operator import itemgetter

list_to_sort=[('89372', 2), ('89373', 1), ('89374', 1), ('89375', 1), ('89376', 1),     ('89377', 1), ('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)]
print list_to_sort

list_to_sort.sort()
print list_to_sort # badly sorted as described

list_to_sort.sort(key=itemgetter(0))
print list_to_sort # badly sorted as described (same as above)

list_to_sort.sort(key=lambda x: int(x[0]))
print list_to_sort # sorted well

list_to_sort.sort(key=lambda x: int(x[0]), reverse=True)
print list_to_sort # sorted well in reverse

关于构建列表以根据dict进行排序的附带说明iteritems()是一种更好的方法,可以使用以下方法进行排序

dict_List = [(x, FID_GC_dict[x]) for x in FID_GC_dict.keys()]

dict_List = [(k,v) for k,v in FID_GC_dict.iteritems()]

相关问题 更多 >

    热门问题