How to deal with case sensitive sorting for output files? [duplicate]

♀尐吖头ヾ 提交于 2020-01-16 07:03:20

问题


I have written a program that randomly generates a series of 5 letters (ASCII, both upper and lower case) in column 1 of a csv and 4 numbers (0-9) in column 2 of a csv and saves them as a file. I can sort column 2 in order of ascending values but struggle with the column 1 as it sorts all the upper case values first and then lower case. this is also output to a new file ('sorted.csv')

example:

ANcPI
DLBvA
FpSCo
beMhy
dWDjl

does anyone know how to sort these so that upper or lower case does not impact but rather just the letter? It should sort as:

ANcPI
beMhy
DLBvA
dWDjl
FpSCo

回答1:


I ran into this recently as well, and it - assuming your data is in a list - can be solved very simply by specifying the optional key argument:

li = ['ANcPI', 'DLBvA', 'FpSCo', 'beMhy', 'dWDjl']
li.sort(key=lambda m : m.lower())

Then,

>>>print(li)
['ANcPI', 'beMhy', 'DLBvA', 'dWDjl', 'FpSCo']


来源:https://stackoverflow.com/questions/34683129/how-to-deal-with-case-sensitive-sorting-for-output-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!