Abd*_*P M 8 python sorting performance iterator python-2.7
说我有一个字符串a.
a = "12 I have car 8 200 a"
Run Code Online (Sandbox Code Playgroud)
我需要以输出应该这样的方式对这个字符串进行排序
8 a car have 12 200 I
Run Code Online (Sandbox Code Playgroud)
即,对字符串进行排序,使所有单词按字母顺序排列,所有整数按数字顺序排列.此外,如果字符串中的第n个元素是整数,则它必须保持整数,如果是单词则必须保留为单词.
这是我试过的.
a = "12 I have car 8 200 a"
def is_digit(element_):
"""
Function to check the item is a number. We can make using of default isdigit function
but it will not work with negative numbers.
:param element_:
:return: is_digit_
"""
try:
int(element_)
is_digit_ = True
except ValueError:
is_digit_ = False
return is_digit_
space_separated = a.split()
integers = [int(i) for i in space_separated if is_digit(i)]
strings = [i for i in space_separated if i.isalpha()]
# sort list in place
integers.sort()
strings.sort(key=str.lower)
# This conversion to iter is to make use of next method.
int_iter = iter(integers)
st_iter = iter(strings)
final = [next(int_iter) if is_digit(element) else next(st_iter) if element.isalpha() else element for element in
space_separated]
print " ".join(map(str, final))
# 8 a car have 12 200 I
Run Code Online (Sandbox Code Playgroud)
我得到了正确的输出.但我使用两个单独的排序函数来排序整数和单词(我认为这是昂贵的).
是否可以使用单个排序函数进行整个排序?
numpy 允许更简洁地编写它,但并没有消除对两种单独排序的需要:
$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> from numpy.core.defchararray import isdecimal, lower
>>>
>>> s = "12 I have car 8 200 a"
>>>
>>> a = np.array(s.split())
>>>
>>> integer_mask = isdecimal(a)
>>> string_mask = ~integer_mask
>>> strings = a[string_mask]
>>>
>>> a[integer_mask] = np.sort(np.int_(a[integer_mask]))
>>> a[string_mask] = strings[np.argsort(lower(strings))]
>>>
>>> ' '.join(a)
'8 a car have 12 200 I'
Run Code Online (Sandbox Code Playgroud)