将列表中的特定值更改为整数

2024-07-03 04:28:21 发布

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

我一直在试着让一个程序根据请求的项目打印出一个排序的列表。当我从CSV文件请求列表时,我不知道如何将4个值中的2个设置为整数,因为当它在程序中显示时,数字被视为字符串,并且不能正确排序。你知道吗

例如:

['Jess','F','2009','6302']

['Kat'、'F'、'1999'、'6000']

['Alexander','M','1982','50']

['Bill'、'M'、'2006'、'2000']

[“杰克”,“M”,“1998”,“1500”]

def sortD(choice):
            clear()
            csv1 = csv.reader(open('TestUnsorted.csv', 'r'), delimiter=',')
            sort = sorted(csv1, key=operator.itemgetter(choice))
            for eachline in sort:
                    print (eachline)
            open('TestUnsorted.csv', 'r').close()

            #From here up is where I'm having difficulty

            with open('TestSorted.csv', 'w') as csvfile:
                    fieldnames = ['Name', 'Gender', 'Year','Count']
                    csv2 = csv.DictWriter(csvfile, fieldnames=fieldnames, 
                    extrasaction='ignore', delimiter = ';')
                    csv2.writeheader()
                    for eachline in sort:
                            csv2.writerow({'Name': eachline[0] ,'Gender': eachline[1],'Year':eachline[2],'Count':eachline[3]})
                            List1.insert(0, eachline)
            open('TestSorted.csv', 'w').close

下面是我的TestUnsorted文件的样子:

杰克,M,19981500

比尔,M,20062000

凯特,女,19996000

杰斯,女,20096302

亚历山大,M,1982,50


Tags: 文件csv程序列表for排序opensort
1条回答
网友
1楼 · 发布于 2024-07-03 04:28:21
sort = sorted(csv1, key=lambda ch: (ch[0], ch[1], int(ch[2]), int(ch[3])))

将最后两个值作为整数排序。你知道吗

编辑:

进一步阅读这个问题后,我意识到choice是您要排序的列表的索引。你可以这样做:

        if choice < 2: # or however you want to determine whether to cast to int
            sort = sorted(csv1, key=operator.itemgetter(choice))
        else:
            sort = sorted(csv1, key=lambda ch: int(ch[choice]))

相关问题 更多 >