排序 csv 列表(不使用 csv 模块)

Sorting csv list (without using csv module)

我有一个包含大约 10 行数据的 csv 文件,格式如下:

Attendees
ID, name, location, age
001, John, Harper, 53
002, Lucy, Jones, 23 
etc...

我需要将其导入 python,然后按年龄对记录进行排序。我想使用某种比较循环来做到这一点(这是我们在 class 中学到的)。

我已将记录作为一个长列表导入 python 并将其拆分为单独的记录,但我在如何将年龄值转换为整数方面遇到了问题(尝试了 int(item[ 3]) 但我收到了一条错误消息)以及我如何一个一个地遍历列表并引用最后一个列表而没有单独的名称。

这是我目前拥有的:

text_file = open("attendees.csv", "r")
lines = text_file.readlines()
print(lines)
new_list = []
for line in lines:
    item = line.strip().split(',')
    new_list.append(item)
print (new_list)
text_file.close()

您需要跳过输入的前两行。你不能转换例如age 和整数。

首先,您需要跳过文件中的标题和 header 行,以防止排序中断。接下来将所有行读入列表。最后根据 age 列的整数值对行进行排序:

with open('attendees.csv', 'r') as f_input:
    title = next(f_input)
    header = next(f_input)
    rows = [[col.strip('\n ') for col in row.split(',')] for row in f_input]

for row in sorted(rows, key = lambda x: int(x[3])):
    print row

这将为您的示例输入显示以下输出:

['002', 'Lucy', 'Jones', '23']
['001', 'John', 'Harper', '53']

请注意,在处理文件时始终使用 Python 的 with 关键字更为安全。这确保当脚本超出其范围时文件自动关闭。