![](/img/trans.png)
[英]How to sort a list/tuple of lists/tuples by the element at a given index?
[英]how to index the last element of a tuple in a list of tuples
我有一個元組列表,其中包含多個(1至更多,數量各不相同)元組。 例如,
[(5, 5), ((5, 5), (4, 5)), ((5, 5), (4, 2), (3, 3))]
我想索引每個元組的最后一個元素,
#ideal result
(5, 5,) (4, 5) (3, 3)
我嘗試了以下
if len(n) == 1: #n is the iterator
print n[0]
else
print n[-1]
但是,對於第一個元素,它打印5而不是(5,5)
for item in theList:
last = item[-1] # could be an int or a tuple
if isinstance(last, tuple):
print last
else:
print item
此代碼中的關鍵思想是isinstance()
測試。 相關的doco是:
isinstance(object,classinfo)
如果object參數是classinfo參數或其(直接,間接或虛擬)子類的實例,則返回true。 如果classinfo是類型對象(新樣式類)並且object是該類型的對象或其(直接,間接或虛擬)子類的對象,則還返回true。 如果object不是類實例或給定類型的對象,則該函數始終返回false。 如果classinfo是類或類型對象的元組(或遞歸,其他類似的元組),則如果object是任何類或類型的實例,則返回true。 如果classinfo不是類,類型或類,類型以及此類元組的元組,則會引發TypeError異常。
l = [(5, 5), ((5, 5), (4, 5)), ((5, 5), (4, 2), (3, 3))]
[ t[-1] if isinstance(t[-1], tuple) else t for t in l ]
輸出:
[(5, 5), (4, 5), (3, 3)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.