对python列表进行排序,使字母位于数字之前

2024-04-26 02:46:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python很陌生,我正在寻找一种将单词放在数字之前的列表排序方法。

我知道您可以使用sort执行以下操作:

a = ['c', 'b', 'd', 'a']
a.sort()
print(a)
['a', 'b', 'c', 'd']

b = [4, 2, 1, 3]
b.sort()
print(b)
[1, 2, 3, 4]

c = ['c', 'b', 'd', 'a', 4, 2, 1, 3]
c.sort()
print(c)
[1, 2, 3, 4, 'a', 'b', 'c', 'd']

不过,我想对c排序以生成:

['a', 'b', 'c', 'd', 1, 2, 3, 4]

提前谢谢


Tags: 方法列表排序数字sort单词print陌生
3条回答
[sorted([letter for letter in c if isinstance(letter, str)]) + \
 sorted([number for number in c if isinstance(number, int)]]

应该这么做。

默认的Python排序是asciibetical

给出:

>>> c = ['c', 'b', 'd', 'a', 'Z', 0, 4, 2, 1, 3]

默认排序为:

>>> sorted(c)
[0, 1, 2, 3, 4, 'Z', 'a', 'b', 'c', 'd']

在Python3上也不起作用:

Python 3.4.3 (default, Feb 25 2015, 21:28:45) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> c = ['c', 'b', 'd', 'a', 'Z', 0, 4, 2, 1, 3]
>>> sorted(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()

解决方案是创建一个元组,其中索引整数作为第一个元素(基于项类型),项本身作为下一个元素。Python 2和3将使用第二个元素异类类型对元组进行排序。

给出:

>>> c = ['c', 'b', 'd', 'a', 'Z', 'abc', 0, 4, 2, 1, 3,33, 33.333]

注意字符、整数、字符串、浮点数的混合

def f(e):
    d={int:1, float:1, str:0}
    return d.get(type(e), 0), e

>>> sorted(c, key=f)   
['Z', 'a', 'abc', 'b', 'c', 'd', 0, 1, 2, 3, 4, 33, 33.333]

或者,如果你想要羔羊:

>>> sorted(c,key = lambda e: ({int:1, float:1, str:0}.get(type(e), 0), e)))  
['Z', 'a', 'abc', 'b', 'c', 'd', 0, 1, 2, 3, 4, 33, 33.333]

根据“狼”的评论,你还可以:

>>> sorted(c,key = lambda e: (isinstance(e, (float, int)), e))
['Z', 'a', 'abc', 'b', 'c', 'd', 0, 1, 2, 3, 4, 33, 33.333]

但我必须同意。。。

您可以提供一个自定义的key参数,它给字符串的值比给int的值低:

>>> c = ['c', 'b', 'd', 'a', 4, 2, 1, 3]
>>> c.sort(key = lambda item: ([str,int].index(type(item)), item))
>>> c
['a', 'b', 'c', 'd', 1, 2, 3, 4]

相关问题 更多 >