如何对列表进行排序,仅对字符串进行排序? [英] How to sort a list, only sorting strings?
问题描述
我有一个字符串和整数列表,想要对列表进行排序,并像这样保留数字
I have a list of strings and integers and want to sort the list, preserving the numbers like so
["Hello", 1, 2, "World", 6, "Foo", 3]
将成为
["Foo", 1, 2, "Hello", 6, "World", 3]
简而言之,它仅对列表中的字符串进行排序,而不对保留在原位的整数进行排序.我尝试将key
参数与list.sort()
一起使用,但未能实现我想要的.
In short, it only sorts the strings in the list, not the integers, which stay in place. I've tried using the key
parameter with list.sort()
but haven't managed to achieve what I want.
有人可以帮我吗?
这与链接的问题不同,因为我想保留整数的索引,而不是将它们与字符串一起排序.
this is different to the linked question as I want to preserve the integers' indexes, rather than sort them along with the strings.
这与第二个链接的问题不同,因为该问题的答案可以使用key
参数解决问题,我明确声明的内容在这种情况下不起作用.
this is different to the second linked question as answers from that question can solve the problem using the key
parameter, something I have explicitly stated does not work in this instance.
推荐答案
前几天从@JonClements挑选了这个很棒的技巧.
Picked up this cool trick from @JonClements the other day.
在这里:
gen = iter(sorted([x for x in lst if isinstance(x, str)]))
new_lst = [next(gen) if isinstance(x, str) else x for x in lst]
print(new_lst)
# ['Foo', 1, 2, 'Hello', 6, 'World', 3]
分别对字符串进行排序,然后根据排序后的字符串创建生成器表达式.在列表理解中,从gen中交替选择对象.经验如果只有原始位置中的项目是字符串,则使用三元条件,否则,请从初始列表中选择一个项目(整数).
Sort the strings separately and create a generator expression from the sorted strings. In a list comprehension, pick objects alternately from the gen. exp. using a ternary conditional if only the items in the original position is a string, otherwise, pick an item (an integer) from the initial list.
这篇关于如何对列表进行排序,仅对字符串进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!