簡體   English   中英

反轉列表列表或元組列表的順序

[英]Reversing the order of a list of lists or list of tuples

我有一個元組列表:

ls = [('hello', 'there'), ('whats', 'up'), ('no', 'idea')]

我想顛倒列表中每個元組的順序。

ls = [('there', 'hello'), ('up', 'whats'), ('idea', 'no')]

我知道元組是不可變的,所以我需要創建新的元組。 我不太確定 go 的最佳方法是什么。 我可以將元組列表更改為列表列表,但我認為 go 可能有更有效的方法。

只需按照以下幾行使用列表推導

ls = [tpl[::-1] for tpl in ls]

這使用典型的[::-1] 切片模式來反轉元組。

另請注意,列表本身不是不可變的,因此如果您需要改變原始列表,而不僅僅是重新綁定ls變量,您可以使用切片賦值

ls[:] = [tpl[::-1] for tpl in ls]

這是基於循環的方法的簡寫形式 à la:

for i, tpl in enumerate(ls):
    ls[i] = tpl[::-1]

輸入:

ls = [('hello', 'there'), ('whats', 'up'), ('no', 'idea')]

ls = [(f,s) for s,f in ls]
print(ls)

Output:

[('there', 'hello'), ('up', 'whats'), ('idea', 'no')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM