【问题标题】:Using a method reverse to sorted list gives error使用反向排序列表的方法会出错
【发布时间】:2021-10-19 15:42:34
【问题描述】:

您好,我有一个地点列表

>>> places = ['NYC','PA', 'SF', 'Vienna', 'Berlin', 'Amsterdam']

我暂时用它排序

>>> sorted(places)

最后我想按字母倒序对已排序的(地点)列表进行排序。

这是正确的吗?

>>> sorted(places).reverse()

我以为是,但 Python3 说列表没有。

谢谢

【问题讨论】:

  • reversed(sorted(places)).reverse() 方法在原地反转列表而不返回任何内容,就像 .sort() 方法在原地排序而不返回任何内容一样。您可能还必须执行list(reversed(sorted(places))),因为reversed() 返回一个需要强制转换为列表的生成器。
  • 感谢您的建议。我可能会使用更多变量来简化代码流程,至少对我来说是这样。

标签: python-3.x list


【解决方案1】:

这里有几个例子:

你的名单:

places = ['NYC','PA', 'SF', 'Vienna', 'Berlin', 'Amsterdam']

使用带有反向参数的排序方法

places.sort(reverse=True)
print(places)

在新变量上使用排序和反向方法,因为排序方法需要一个:

testlist=sorted(places)
testlist.reverse()
print(testlist)

使用带有反向的排序方法参数:

testlist1=sorted(places, reverse=True)
print(testlist1)

【讨论】:

    【解决方案2】:
    print(sorted(places,reverse=True))
    

    或者你可以使用变量

    other_list=sorted(places,reverse=True)
    print(other_list)
    

    【讨论】:

      猜你喜欢
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      相关资源
      最近更新 更多