简体   繁体   English

如何对包含数字的字符串列表进行数字排序?

[英]How to numerically sort list of strings containing numbers?

f1 = open("leader")
lines = f1.readlines()
lines.sort(key=int, reverse=True)
f1.close()
print(lines)

with external file values: 使用外部文件值:

345345:player7
435:zo
345:name
23:hello
1231:football

this is to sort them so that the integers are sorted not the names 这是为了对它们进行排序,以便整数排序而不是名称

IIUC: IIUC:

l = ['345345:player7',
'435:zo',
'345:name',
'23:hello',
'1231:football']

sorted(l, key=lambda x: int(x.split(':')[0]))

Output: 输出:

['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']

The sort key should do: "split once, convert to integer". 排序键应该:“拆分一次,转换为整数”。 Not converting to integer fails because then lexicographical compare is used and in that case "10" < "2" , not that you want. 不转换为整数失败,因为然后使用词典比较,在那种情况下"10" < "2" ,而不是你想要的。

l = ['345345:player7',
'435:zo',
'345:name',
'23:hello',
'1231:football']

result = sorted(l, key=lambda x: int(x.split(':',1)[0]))

result: 结果:

['23:hello', '345:name', '435:zo', '1231:football', '345345:player7']

that doesn't handle the tiebreaker where numbers are equal. 这不能处理数字相等的决胜局。 A slightly more complex sort key would be required (but still doable). 需要稍微复杂的排序键(但仍然可行)。 In that case, drop lambda and create a real function so you can perform split once & unpack to convert only the first part to integer: 在这种情况下,删除lambda并创建一个实际函数,这样你就可以执行split一次&unpack将第一部分转换为整数:

def sortfunc(x):
    number,rest = x.split(':',1)
    return int(number),rest

result = sorted(l, key=sortfunc)

Try this: (helpful if you are still reading from a file) 试试这个:(如果您还在从文件中读取,则会很有帮助)

with open('leader.txt', mode = 'r') as f1:
    data = f1.readlines()
# end with
keys = {}
output = []
for s in data:
    num, value = s.split(sep=':')
    if keys.get(int(num), False):
        keys[int(num)].append(value)
    else:
        keys[int(num)] = [value]
for num in sorted(keys):
    for i in keys[num]:
        output.append((num, i))
for num, value in output:
    print(f'{num}: {value}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM