简体   繁体   中英

how to index the last element of a tuple in a list of tuples

I have a list of tuples that contains multiple(1 to more, number varies) tuples. For example,

[(5, 5), ((5, 5), (4, 5)), ((5, 5), (4, 2), (3, 3))]

I would like to index the last element of each tuple,

#ideal result
(5, 5,) (4, 5) (3, 3)

I have tried the following

 if len(n) == 1: #n is the iterator
        print n[0]
    else
        print n[-1]

however, for the first element, it print 5 instead of (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

The key idea in this code is the isinstance() test. The related doco is:

isinstance(object, classinfo)

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct, indirect or virtual) subclass thereof. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is a tuple of class or type objects (or recursively, other such tuples), return true if object is an instance of any of the classes or types. If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised.

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 ]

Output:

[(5, 5), (4, 5), (3, 3)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM