gpt4 book ai didi

python - 用整数和单词对字符串进行排序,而不改变它们的位置

转载 作者:太空狗 更新时间:2023-10-29 20:41:28 25 4
gpt4 key购买 nike

假设我有一个字符串 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

我得到了正确的输出。但是我使用两个单独的排序函数来对整数和单词进行排序(我认为这很昂贵)。

是否可以使用单个排序函数进行整个排序?

最佳答案

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'

关于python - 用整数和单词对字符串进行排序,而不改变它们的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47311720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com