Better way to swap elements in a list?

后端 未结 14 1325
臣服心动
臣服心动 2020-12-23 13:32

I have a bunch of lists that look like this one:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to swap elements as follows:

fi         


        
14条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 14:21

    For fun, if we interpret "swap" to mean "reverse" in a more general scope, the itertools.chain.from_iterable approach can be used for subsequences of longer lengths.

    l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    def chunk(list_, n):
        return (list_[i:i+n] for i in range(0, len(list_), n))
    
    list(chain.from_iterable(reversed(c) for c in chunk(l, 4)))
    # [4, 3, 2, 1, 8, 7, 6, 5, 10, 9]
    

提交回复
热议问题