python - 如何在Python中按升序对前半部分进行升序对后半部分进行降序排序?

标签 python list for-loop while-loop

我有一个 python 列表 [1,2,3,4,5],我必须打印 [1,2,3,4,5,5,4,3,2,1]。

请建议如何在循环中执行操作(while 或 for)

最佳答案

使用for循环:

>>> l = [1, 2, 3, 4, 5]
>>> res = []
>>> for e in reversed(l):
...     res.append(e)
...     res.insert(0, e)
>>> res
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]

如果列表未排序,请使用 sorted 代替 reversed,并将反向标志设置为 True

>>> l = [4, 3, 1, 5, 2]
>>> res = []
>>> for e in sorted(l, reverse=True):
...     res.append(e)
...     res.insert(0, e)
... 
>>> res
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]

并且,为了获得更高效的版本,我建议使用迭代器:

>>> import itertools
>>> l = sorted([4, 3, 1, 5, 2])
>>> res = list(itertools.chain(l, reversed(l)))
>>> res
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]

关于python - 如何在Python中按升序对前半部分进行升序对后半部分进行降序排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53097331/

相关文章:

python - 如何使用 selenium xpath 单击登录按钮

python - Github Actions Build - 在多个文件夹上推送到 ECR

python:将列表的每个元素组合到元组列表

Python while 和 for 循环 - 我可以使代码更高效吗?

matlab - 用于创建重复元素向量的 for/while/if 程序

python - 如果可能,python 会重用列表吗?

python - Selenium - 从 highcharts 获取数据

r - 使用 cbind 将向量与向量列表绑定(bind)

python - 气泡排序开关和旋转挑战

java - 反序列化对象并将其添加到数组中