简体   繁体   中英

How do I “truncate” the last column of a tuple of same length tuples?

Suppose I have

x = ((1, 2, 3), (4, 5, 6), (7, 8, 9))

How do I get to

x = ((1, 2), (4, 5), (7, 8))

?

The only way I figured out was using list comprehension then converting back to a tuple:

x = tuple([n[1:len(n)] for n in x])

But I feel that's an ugly way of doing it...

In [1]: x = ((1, 2, 3), (4, 5, 6), (7, 8, 9))

In [2]: tuple(a[:-1] for a in x)

You can use a generator expression instead of a list comprehension (which are almost the same thing):

x = tuple(n[1:] for n in x)

Note though that this will not give you what you had above. If you want to cut off the end you really should do:

x = tuple(n[:-1] for n in x)

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