我正在尝试对一个csv文件进行排序,该文件如下所示:
filename,field1,field2
10_somefile,0,0
1_somefile,0,0
2_somefile,0,0
3_somefile,0,0
4_somefile,0,0
5_somefile,0,0
6_somefile,0,0
7_somefile,0,0
8_somefile,0,0
9_somefile,0,0
我引用了另一个线程的代码:
with open(outfname, "rb") as unsorted_file:
csv_f = csv.reader(unsorted_file)
header = next(csv_f, None)
sorted_data = sorted(csv_f, key=operator.itemgetter(0))
with open(outfname, 'wb') as sorted_file:
csv_f = csv.writer(sorted_file, quoting=csv.QUOTE_ALL)
if header:
csv_f.writerow(header)
csv_f.writerows(sorted_data)
但是,这不会将“10\u somefile”移到末尾。如何排序,使其使用下划线前的数字作为排序字段?你知道吗
发生这种情况是因为“10”<;“1”。你想比较整数,而不是字符串。可以通过为每一行创建一个整数来实现此行为,该整数使用下划线以下的字符。假设您可以获得一个字符串
s
(这可以像您当前所做的那样使用itemgetter来完成)。然后,下面的lambda(作为key
传递给sorted
)将执行您想要的操作。你知道吗这个函数的作用很简单:它只返回由
s
的字符组成的整数,直到但不包括第一个下划线。你知道吗假设所有的
filename
字段都以一个数字开头,那么最简单的方法就是将整数从文件名中解析出来,按整数排序。你知道吗如果您输出
sorted_data
,它应该如下所示:sorted
的key
参数返回每行的第一个元素作为字符串,使"10..."
位于"1_..."
之前。您需要使用“自然排序”而不是这种原始排序。你知道吗检查How to correctly sort a string with a number inside?
相关问题 更多 >
编程相关推荐