简体   繁体   中英

How can i remove the even number indexes in a list of tuples?

I have a tuple list like this:

   lis__ = [('string', 'id1',...,'string', 'idn')]

With different ids and strings . How can I remove the ids from this tuple list?, the ids look like this DSDF2342 and they are different. For example:

   lis__ = [('string', '234SDFSD',...,'string', 'DFSFSD234')]

The desired output would be something like this:

[(string string .... string)]

Thanks in advance guys. This is what I tried:

my_list = [tuple([j.split()[0] for j in i]) for i in lis__]

print my_list

A good solution:

my_list = [t[::2] for t in lis__]

The slice t[::2] takes only items with an even index (0, 2, 4, &c).

This will give you a list of items that do not contain items that startwith "id":

t = ('string', 'id1',...,'string', 'idn')
no_ids = [ item for item in t if not item.startswith("id")]

If you want to remove the odd indexed items you can also use range() , to provide the desired indexes. ( Where the positional arguments are range(start, stop, step) ):

t = ('string', 'id1',...,'string', 'idn')
no_ids = [ t[idx] for idx in range(0, len(t), 2)]

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