简体   繁体   中英

How to sort a list according to the parity of the index of an item in Python

For example, I have:

a = ["a","b","c","d"]

I want to create a function (a key) such that:

def myfunc(a_list_of_items):
    # I have no idea what to do after this

a.sort(key=myfunc)
print(a)

Output should be:

["a","c","b","d"] #elements that had odd index -
# - stacked at one side and those with even stacked on the other

How about the following (uses Python's slice notation ):

a[::2] + a[1::2]

This will result in:

['a', 'c', 'b', 'd']

Here, the sorted() function is not very appropriate in my opinion.

I would might use

[x for (_, x) in sorted(enumerate(a), key=lambda i: i[0] % 2)]

First, enumerate creates a list of index/value pairs from the original list. The given key function extracts the index and finds the remainder modulo 2; even indices are 0 and odd indices are 1, so that is sufficient to get the order you want. The list comprehension then extracts the original values from the sorted list of index/value pairs.

(For the given problem, concatenating two slices is certainly simpler, although possibly more costly. Benchmarking would determine which of the two approaches is faster/more efficient.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM