您的位置:首页 > 编程语言 > Python开发

Python 中的sort()排序

2018-03-29 19:38 120 查看

v = [1, 3, 5, 2, 4, 6]
v.sort()
print(v)  # [1, 2, 3, 4, 5, 6]

v2 = [(1, 2), (2, 2), (2, 3), (3, 1)]
v2.sort()
print(v2)  # [(1, 2), (2, 2), (2, 3), (3, 1)]

v3 = [(1, 2), (2, 2), (2, 3), (3, 1)]
v3.sort(key=lambda x: (x[1], x[0]))
print(v3)  # [(3, 1), (1, 2), (2, 2), (2, 3)]

面试题:

1:

sorted_lines = sorted(open("Uin_Age.txt"), key=lambda x: (x.split()[1]))
for i in sorted_lines:
print(i,end='')

2:

open("output.txt", 'w').write("".join(sorted_lines))
l2 = []
f = open("Uin_Age.txt")
for line in f.readlines():
l = line.split(' ')
l1 = l[-1].split('\n')
t = {"x": l[0], "y": int(l1[0])}
l2.append(t)
l2.sort(key=lambda item: item['y'])
for i in l2:
print(i["x"] + ' ' + str(i['y']))

如果写入文件:

sorted_lines = sorted(open("Uin_Age.txt"), key=lambda x: (x.split()[1]))
open("output.txt", 'w').write("".join(sorted_lines))

  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: