如何删除 3-ples 列表中每个元组的第二个元素?
How to remove the 2nd element of every tuple in a list of 3-ples?
我有一个像这样的大清单:
list__=[('string id1', 'string id2', 'string id3'), ('string id4', 'string id5', 'string id6'), ... ,('string idn', 'string id', 'string idn-1')]
如何从这个大元组中删除 ID,例如:
[('string', 'string', 'string'), ('string', 'string', 'string'), ... ,('string', 'string', 'string')]
知道我该如何解决这个问题吗?我试过:
OutputTuple = [(a, b, d) for a, b, c, d in ListTuple]
但它只是删除了第二个元素。
使用列表理解:
my_list = [tuple([j.split()[0] for j in i]) for i in my_list]
解包比使用双 for 循环更有效:
[(a.split()[0], b.split()[0], c.split()[0]) for a, b, c in list__ ]
您还可以索引到空白:
[(a[:a.index(" ")], b[:b.(" ")], c[:c.index(" ")]) for a,b,c in list__ ]
有趣的是,使用 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
我有一个像这样的大清单:
list__=[('string id1', 'string id2', 'string id3'), ('string id4', 'string id5', 'string id6'), ... ,('string idn', 'string id', 'string idn-1')]
如何从这个大元组中删除 ID,例如:
[('string', 'string', 'string'), ('string', 'string', 'string'), ... ,('string', 'string', 'string')]
知道我该如何解决这个问题吗?我试过:
OutputTuple = [(a, b, d) for a, b, c, d in ListTuple]
但它只是删除了第二个元素。
使用列表理解:
my_list = [tuple([j.split()[0] for j in i]) for i in my_list]
解包比使用双 for 循环更有效:
[(a.split()[0], b.split()[0], c.split()[0]) for a, b, c in list__ ]
您还可以索引到空白:
[(a[:a.index(" ")], b[:b.(" ")], c[:c.index(" ")]) for a,b,c in list__ ]
有趣的是,使用 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