当行以字符串开头时,如何按整数对文本文件排序?

2024-05-16 22:36:55 发布

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

当行以字符串开头时,如何按整数对文本文件排序?你知道吗

我想列这个单子

Adams   3.7
Alexander   36.1
Bond    6.5
Boone   2.6
Brown   19.1
Bureau  0.8
Calhoun     0.3
Carroll     1.1
Cass    4.4
Champaign   12.8

就像

Calhoun     0.3
Bureau  0.8
Carroll     1.1
Boone   2.6
Adams   3.7
Cass    4.4
Bond    6.5
Champaign   12.8
Brown   19.1
Alexander   36.1

然后我还计划删除所有值大于1的行,然后删除所有整数。你知道吗


Tags: 字符串排序整数单子文本文件alexanderbrownbureau
2条回答

这会有用的!你知道吗

fp = open('file')

pairs = [line.split() for line in fp]

fp.close()

# pair = [['Adams', '3.7'], ['Alexander', '36.1'], ['Bond', '6.5'], ['Boone', '2.6'], ['Brown', '19.1'],
#         ['Bureau', '0.8'], ['Calhoun', '0.3'], ['Carroll', '1.1'], ['Cass', '4.4'], ['Champaign', '12.8']]

pairs.sort(key=lambda item: float(item[1]))
print(pairs)
# pairs = [['Calhoun', '0.3'], ['Bureau', '0.8'], ['Carroll', '1.1'], ['Boone', '2.6'], ['Adams', '3.7'], ['Cass', '4.4'],
#          ['Bond', '6.5'], ['Champaign', '12.8'], ['Brown', '19.1'], ['Alexander', '36.1']]

fp = open('result', 'w')

for pair in pairs:
    string = str(pair[0]) + '   ' + str(pair[1]) + '\n'
    fp.write(string)

fp.close()
# open file
with open("my_file.txt") as infile:
    # make a list with each line
    # split lines by whitespace, so that the name is element 0 and value is element 1
    file_lines = [line.split() for line in infile]

# sort lines, with the sort key being the value (element 1)
# we need to cast it to a float first, so that numeric comparison behaves correctly
sorted_lines = sorted(file_lines, key=lambda x:float(x[1]))
print(sorted_lines)
# [['Calhoun', '0.3'], ['Bureau', '0.8'], ['Carroll', '1.1'], ['Boone', '2.6'], ['Adams', '3.7'], ['Cass', '4.4'], ['Bond', '6.5'], ['Champaign', '12.8'], ['Brown', '19.1'], ['Alexander', '36.1']]

# export back to file in the same format
outfile_lines = ["\t".join(line) for line in sorted_lines]
with open("my_file_sorted.txt", "w") as outfile:
    outfile.writelines(outfile_lines)

您可以稍后进一步过滤sorted_lines。例如:

filtered_lines = [line for line in file_lines
                     if float(line[1]) <= 1  # "remove all lines with value greater than 1"
                     and float(line[1]) != float(int(line[1]))  # "remove all of the integers"
                 ]

相关问题 更多 >