对具有保持在固定位置的特定值的列表进行排序

cai*_*ing 1 python sorting algorithm python-3.x

我有一个字符串列表.我只想对符合特定条件的值进行排序.考虑这个清单

['foo','bar','testa','python','java','abc']
Run Code Online (Sandbox Code Playgroud)

我只想用其中的值对值进行排序a.结果应该是这样的

['foo','abc','bar','python','java','testa']
Run Code Online (Sandbox Code Playgroud)

具有的元素a将适当地改变位置,但其他元素保留其原始位置.

我完全不知道如何实现这一点,所以我希望其他人这样做.有人能告诉我怎么做吗?

Eso*_*oid 6

y = sorted(w for w in x if 'a' in w)  # pick and sort only the elements with 'a'
x = [w if 'a' not in w else y.pop(0) for w in x]
Run Code Online (Sandbox Code Playgroud)

最后一行留下没有'a'更改的单词,而'a'从y列表中逐步选择那些(已经排序)

编辑:@MartijnPieters解决方案表现更好,因为它使用迭代器,不会使用额外的内存来存储y.

y = iter(sorted(w for w in x if 'a' in w))  # create iterator, don't use memory
x = [w if 'a' not in w else next(y) for w in x]  # yield from iter instead of popping from a list
Run Code Online (Sandbox Code Playgroud)

由于看起来你需要这个算法来处理不同的条件,你可以把它放到一个方法中:

x = ['foo','bar','testa','python','java','abc']

def conditional_sort(ls, f):
    y = iter(sorted(w for w in ls if f(w)))
    return [w if not f(w) else next(y) for w in ls]

conditional_sort(x, lambda w: 'a' in w)
Run Code Online (Sandbox Code Playgroud)

第一个参数是列表,第二个参数是一个接受单个参数并返回bool值的函数.

  • `sorted()`已经返回一个列表,你的`list()`调用是多余的.如果你使用迭代器(`y = iter(sorted(...))`和`else next(y)`)会更有效率. (2认同)