【发布时间】:2017-11-15 15:48:55
【问题描述】:
假设我有一个字符串 a。
a = "12 I have car 8 200 a"
我需要对这个字符串进行排序,使得输出应该是
8 a car have 12 200 I
即,对字符串进行排序,使所有单词按字母顺序排列,所有整数按数字顺序排列。此外,如果字符串中的第 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
我得到了正确的输出。但是我使用两个单独的排序函数对整数和单词进行排序(我认为这很昂贵)。
是否可以使用单个排序函数完成整个排序?
【问题讨论】:
标签: python python-2.7 performance sorting iterator