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

时间:2019-07-16 15:34:46

标签: python python-2.7

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

我想列出这个清单

<a [routerLink]="['/myExternalLink', {url: 'http://sunbeam.com'}]">Link to sunbeam</a>

喜欢

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

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

2 个答案:

答案 0 :(得分:2)

# 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"
                 ]

答案 1 :(得分:0)

这将起作用!

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()