我有一个列表a = ['L','N','D']。我想颠倒a中元素的顺序并得到b = ['D','N','L']。我尝试这样做:按相反顺序对列表进行排序
a = ['L', 'N', 'D']
b = sorted(a, reverse=True)
但输出
b= ['N', 'L', 'D']
我在哪里犯了一个错误?
我有一个列表a = ['L','N','D']。我想颠倒a中元素的顺序并得到b = ['D','N','L']。我尝试这样做:按相反顺序对列表进行排序
a = ['L', 'N', 'D']
b = sorted(a, reverse=True)
但输出
b= ['N', 'L', 'D']
我在哪里犯了一个错误?
您的错误是使用sorted
,它按照元素的顺序重新排列列表,并忽略元素过去的位置。取而代之的是使用
b = a[::-1]
它以相反的顺序贯穿列表a
。你也可以使用
b = list(reversed(a))
虽然第一个版本是快。
您也可以扭转的地方:
>>> a = ['L', 'N', 'D']
>>> a.reverse()
>>> a
['D', 'N', 'L']
但请注意它的变化列表中,不产生(返程)一个新的。
第一次你几乎是正确的。试试这个:
#This will sort the list temporarily into reverse alphabetical order.
print(sorted(a, reverse=True)
#This will sort the list temporarily into reverse order.
print(sorted(a, reverse=False)
如果你想使用排序(),您可以指定索引排序的关键:
b = sorted(a, key=a.index, reverse=True)
'sorted'是一个内置函数,为了您的带有字母算法的“str”元素,而不仅仅是用于反转序列。在你的内核中使用'help(sorted)'来查看细节。 – Feishi