简体   繁体   English

如何删除三元组列表中每个元组的第二个元素?

[英]How to remove the 2nd element of every tuple in a list of 3-ples?

I have a big list like this: 我有一个像这样的大清单:

list__=[('string id1', 'string id2', 'string id3'), ('string id4', 'string id5', 'string id6'), ... ,('string idn', 'string id', 'string idn-1')]

How can I drop the ids from this big tuple, for example: 我如何从这个大元组中删除ID,例如:

[('string', 'string', 'string'), ('string', 'string', 'string'), ... ,('string', 'string', 'string')]

Any idea of how can I aproach this?. 关于如何提出建议的任何想法? I tried with: 我尝试了:

OutputTuple = [(a, b, d) for a, b, c, d in ListTuple]

But it just drop the second element. 但它只是删除了第二个元素。

使用列表理解:

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

Unpacking will be more efficient than using a double for loop: 解压缩比使用double for循环更有效:

[(a.split()[0], b.split()[0], c.split()[0]) for a, b, c in  list__ ]

You could also index to the whitespace: 您还可以索引空白:

  [(a[:a.index(" ")], b[:b.(" ")], c[:c.index(" ")]) for a,b,c in  list__ ]

Interestingly using str.find is the most efficient solution using python2.7. 有趣的是,使用str.find是使用python2.7的最有效解决方案。

In [41]: timeit [(a[:a.find(" ")], b[:b.find(" ")], c[:c.find(" ")]) for a,b,c in  list__ ]
100000 loops, best of 3: 2.27 µs per loop

In [42]: timeit [tuple([j.split()[0] for j in i]) for i in list__]
100000 loops, best of 3: 3.85 µs per loop

In [43]: timeit [(a.split()[0], b.split()[0], c.split()[0]) for a, b, c in  list__ ]
100000 loops, best of 3: 2.73 µs per loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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