我尝试使用 sorted 进行排序
dir =["A1","A2","A10","A3"]
sorted(dir)
我预期的数组是
["A1","A2","A3","A10"]
但实际结果是
["A1", "A10", "A2", "A3"]
如何在python中按名称对数组进行排序?
我尝试使用 sorted 进行排序
dir =["A1","A2","A10","A3"]
sorted(dir)
我预期的数组是
["A1","A2","A3","A10"]
但实际结果是
["A1", "A10", "A2", "A3"]
如何在python中按名称对数组进行排序?
它是按字母顺序排序的,因此您需要分解数字并将它们转换为整数并以此进行排序。(字符串中的数字被视为只是字符,因此它“看到”“A10”并尝试先按“A”排序,然后按“1”,然后按“0”。)例如:
>>> sorted(dir, key=lambda x: int(x[1:]))
['A1', 'A2', 'A3', 'A10']
如果除了 "A" 之外还有其他字母dir
,您将需要一种更复杂的排序方法,但这将是相同的方法。(如果您解释dir
包含更多内容,我可以为此编写一个示例。)正如 mgilson 的评论指出的那样,如果元素dir
遵循 1 char + number 格式,那么您可以利用元组排序并执行以下操作:
>>> dir.append('B12')
>>> sorted(dir, key=lambda x: (x[0],int(x[1:])))
['A1', 'A2', 'A3', 'A10', 'B12']
为了扩展这个问题,我必须以自然的方式对接口名称进行排序。让它变得更复杂的是接口可以有多种风格......你有传统的,比如lo
,eth0
等等......还有一些更高级的方案,比如enp4s0f1d1
. 解决方案是根据类型拆分它们,将数字转换为整数,并且必须注意确保在相同类型上进行比较。
所以我想出了这个排序函数,它应该是相当防弹的(只要你给它字符串......)
def ethkey(eth):
"""Split an ethernet device name between text and digit groups as int,
allowing consistent sorting of interfaces.
Usage: `sorted(if_list, key=ethkey)`
:param eth: Value to sort
:type eth: str
:return: List of str's (even indexes) and int's (odd indexes) to compare
:rtype: list
"""
keys = []
if not eth:
# If eth is a string it's empty, just return blank list
return keys
# Start with the first character already in last
last, eth = eth[0], eth[1:]
# If last is int we start at offset 1
if last.isdigit():
keys.append('')
for i in eth:
if i.isdigit() is last.isdigit():
# Keep accumulating same type chars
last += i
else:
# Save and restart next round
keys.append(int(last) if last.isdigit() else last)
last = i
# Save final round and return
keys.append(int(last) if last.isdigit() else last)
return keys
然后可以这样使用它:
sorted(int_list, key=ethkey)