【问题标题】:How to sort first half in ascending and second half in descending order in python?如何在python中按升序对前半部分和后半部分按降序排序?
【发布时间】:2019-04-05 10:39:56
【问题描述】:

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

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

【问题讨论】:

  • 列表是否总是默认排序?或者您需要对其进行排序?
  • 正常的方法是对列表进行排序和反转列表并合并2个列表。请以循环方式咨询
  • 它是排序列表
  • @sat 这很浪费,不需要对列表进行两次排序
  • 为什么是负分,我在评论中告诉过,排序和反转我已经完成了。顺便说一下@Netwave 感谢您的回答

标签: python list for-loop while-loop


【解决方案1】:

使用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]

【讨论】:

  • @Netwave,如果列表是l = [1, 2, 3, 4, 5, 1],这将失败
  • @sat,万一列表没有排序,那么他需要使用sorted而不是reversed
【解决方案2】:

试试这个:

a, b = eval('[1,2,3,4,5],'*2);b.reverse();print(a+b)

输出:

C:\Users\Desktop>py x.py
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]

【讨论】:

  • eval 是不好的做法
  • 这背后的主张是什么?
【解决方案3】:

正如你所说的排序列表(对吗?),所以这样做:

print(l+l[::-1])

或者:

print(l+reversed(l))

两种情况,输出都是:

[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]

【讨论】:

    【解决方案4】:

    你不需要循环。只需将源列表与反向列表进行排序和连接。

    a = [2, 1, 5, 4, 3]
    a = sorted(a)
    print(a + a[::-1])
    

    【讨论】:

    • @Netwave 是假的。代码在python3 上也有效。
    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    相关资源
    最近更新 更多