[英]How to Initialize a sorted array in one line instead of creating the array and then sorting it?
I have a code like below:我有如下代码:
print([i if (ord(i)-97)%2 == 0 else i.upper() for i in input()].sort(reverse=True))
the result of this code is None, I couldn't understand why this happened?这段代码的结果是无,我不明白为什么会这样?
.sort()
doesn't return the result. .sort()
不返回结果。 It sorts the given list in place, and so you have no access to it.它对给定的列表进行排序,因此您无权访问它。
Instead, you can use sorted
:相反,您可以使用sorted
:
print(sorted([i if (ord(i)-97)%2 == 0 else i.upper() for i in input()], reverse=True))
Or call sort
on a list you have assigned to a name:或者在您分配给名称的列表上调用sort
:
lst = [i if (ord(i)-97)%2 == 0 else i.upper() for i in input()]
lst.sort(reverse=True)
print(lst)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.