所以我知道如何导入 texfile 并对数字进行排序,例如:
1
6
4
6
9
3
5
但我不知道如何对如下所示的数据进行排序:
Merchant_9976 20122
Merchant_9977 91840
Merchant_9978 92739
Merchant_9979 97252
Merchant_9980 76885
Merchant_9981 67835
Merchant_9982 42201
Merchant_9983 47463
这是我到目前为止的代码
def sort_slow(seq):
for i in range(1, len(seq)):
j = i
while j > 0 and seq[j - 1] > seq[j]:
seq[j - 1], seq[j] = seq[j], seq[j - 1]
j -= 1
return seq
def main():
fileName = str(input('Please enter a filename: '))
file = open(fileName)
sort1 = []
for lines in file:
sort1.append(int(lines.strip()))
sort_slow(sort1)
print(sort1)
main()
我对编码还比较陌生。*大约 1 个月
最佳答案
下面将按右列中的整数排序
with open('file.txt', 'r') as f:
data = f.readlines()
sorted_data = sorted(data, key=lambda i: int(i.split()[1]))
print(sorted_data)
或者,如果您只是希望它们按商家编号排序
with open('file.txt', 'r') as f:
data = f.readlines()
sorted_data = sorted(data)
print(sorted_data)
关于Python 对文本文件进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26246400/