如何根据 Python 中项目索引的奇偶性对列表进行排序
How to sort a list according to the parity of the index of an item in Python
比如我有:
a = ["a","b","c","d"]
我想创建一个函数(一个键):
def myfunc(a_list_of_items):
# I have no idea what to do after this
a.sort(key=myfunc)
print(a)
输出应该是:
["a","c","b","d"] #elements that had odd index -
# - stacked at one side and those with even stacked on the other
我会可能会使用
[x for (_, x) in sorted(enumerate(a), key=lambda i: i[0] % 2)]
首先,enumerate
从原始列表中创建一个包含 index/value 对的列表。给定的 key
函数提取索引并找到余数 modulo 2;偶数索引为 0,奇数索引为 1,因此这足以获得您想要的顺序。然后列表理解从 index/value 对的排序列表中提取原始值。
(对于给定的问题,连接两个切片当然更简单,但可能成本更高。基准测试将确定这两种方法中哪一种 faster/more 有效。)
以下如何(使用Python's slice notation):
a[::2] + a[1::2]
这将导致:
['a', 'c', 'b', 'd']
这里的sorted()
功能在我看来不是很合适
比如我有:
a = ["a","b","c","d"]
我想创建一个函数(一个键):
def myfunc(a_list_of_items):
# I have no idea what to do after this
a.sort(key=myfunc)
print(a)
输出应该是:
["a","c","b","d"] #elements that had odd index -
# - stacked at one side and those with even stacked on the other
我会可能会使用
[x for (_, x) in sorted(enumerate(a), key=lambda i: i[0] % 2)]
首先,enumerate
从原始列表中创建一个包含 index/value 对的列表。给定的 key
函数提取索引并找到余数 modulo 2;偶数索引为 0,奇数索引为 1,因此这足以获得您想要的顺序。然后列表理解从 index/value 对的排序列表中提取原始值。
(对于给定的问题,连接两个切片当然更简单,但可能成本更高。基准测试将确定这两种方法中哪一种 faster/more 有效。)
以下如何(使用Python's slice notation):
a[::2] + a[1::2]
这将导致:
['a', 'c', 'b', 'd']
这里的sorted()
功能在我看来不是很合适