Python 如果满足某些条件,则从元组列表中删除元组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22957606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove tuple from list of tuples if certain condition is met
提问by user781486
I have a list of tuples that look like this;
我有一个看起来像这样的元组列表;
ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]
I want to remove the tuples when the first element of the tuple is less than 50. The OutputList will look like this;
当元组的第一个元素小于 50 时,我想删除元组。OutputList 将如下所示;
OutputList = [(100, 'AAA'), (80, 'BBB')]
How can this be done in python?
这怎么能在python中完成?
Thank you very much for your help.
非常感谢您的帮助。
采纳答案by sshashank124
You can easily do it as:
您可以轻松地做到这一点:
out_tup = [i for i in in_tup if i[0] >= 50]
[Out]: [(100, 'AAA'), (80, 'BBB')]
This simply creates a new list of tuples with only those tuples whose first element is greater than or equal to 50. Same result, however the approach is different. Instead of removing invalid tuples you accept the valid ones.
这只是创建一个新的元组列表,其中仅包含第一个元素大于或等于 50 的那些元组。结果相同,但方法不同。您接受有效的元组而不是删除无效的元组。
回答by Alex Thornton
You can also do:
你也可以这样做:
>>> OutputList = filter(ListTuples, lambda x: x[0] >= 50)
>>> OutputList
[(100, 'AAA'), (80, 'BBB')]
回答by Nishant Nawarkhede
Try this,
尝试这个,
>>> ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]
>>> new=[]
>>> for i in ListTuples:
if i[0]>50:
new.append(i)
>>> new
[(100, 'AAA'), (80, 'BBB')]
>>>
回答by Peter Smit
Code snippet for timing the solutions given by sshashank124 and Alex Thornton:
sshashank124 和 Alex Thornton 给出的用于计时解决方案的代码片段:
ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]
import timeit
timeit.timeit('[i for i in ListTuples if i[0] >= 50]', globals=globals(), number=1000000)
>>> 0.6041104920150246
timeit.timeit('filter(lambda x: x[0] >= 50, ListTuples)', globals=globals(), number=1000000)
>>> 0.3009479799948167
The build-in filter() solution is faster for this example.
对于此示例,内置 filter() 解决方案更快。
回答by keyvan vafaee
We can Do this with simple counter and a new list:
我们可以用简单的计数器和一个新列表来做到这一点:
new = []
for i in ListTuples:
for j in i:
if ( counter % 2 == 0 ):
if ( j > 50):
new.append(i)
counter = counter +1
output :
输出 :
[(100, 'AAA') , (80, 'BBB')]