简体   繁体   English

Python 2.7:按值从列表中删除元组的条件不止一种

[英]Python 2.7: Removing tuples from a list by value basis more than one condition

Suppose I have a list in the following format: 假设我有以下格式的列表:

    [(99.0,0.14),(101.0,0.11),(104.0,4.5),(78.0,14.0)]

I want to iterate over the list of float values, check whether the value in the first index of the tuple is greater than 100 and whether the value in the second index of the tuple is greater than 10 and if either of the above conditions are true subsequently remove the tuple from the list entirely. 我想遍历浮点值的列表,检查元组的第一个索引中的值是否大于100,并且元组的第二个索引中的值是否大于10,并且以上任一条件为真随后将元组从列表中完全删除。

In order to get something like this: 为了得到这样的东西:

    [(99.0,0.14)]

I tried this from @StefanPochmann's answer to the previous version of this question: 我从@StefanPochmann对这个问题的上一版本的回答中尝试了此方法:

    z = [t for t in z if t[0] <= 100 and t[1] <= 10] 

But it returns this error since I am dealing with float values within the tuples of the list: 但由于我正在处理列表的元组中的浮点值,因此它返回此错误:

   TypeError: 'float' object is not iterable

What is the best way to perform this check? 进行此检查的最佳方法是什么?

List comprehension, keep the good tuples. 列表理解,保持良好的元组。

>>> tuples = [(99,78),(101,46),(104,69),(0,32)]
>>> [t for t in tuples if max(t) <= 100]
[(99, 78), (0, 32)]

It's btw not a tuple but a list. 它不是一个元组而是一个列表。

Edit: This is an answer to the original question, not the current answer-invalidating changed one. 编辑:这是对原始问题的答案,而不是当前答案无效的答案。

Based on the solution above: 根据上述解决方案:

lt =  [(99,78),(101,46),(104,69),(0,32)]

# additional function which checks whether the tuple 
# contains elements greater than 100
all_less100 = lambda y: not bool(list(filter(lambda x: x > 100, y)))

# filter tuples that contains elements greater than 100
lt_filtered = list(filter(all_less100, lt))

print(lt_filtered)

The max and min calls don't do anything: you're working with only one value at a time. max和min调用不执行任何操作:您一次只使用一个值。 Get rid of those. 摆脱那些。

    z = [t for t in z if t[0] <= 100 and t[1] <= 10] 
    lt =  [(99,78),(101,46),(104,69),(0,32)]

    lt = filter(lambda x: x[0] < 100,lt)

    print(list(lt))

    [(99, 78), (0, 32)]

    or with list comprehension 

    lt = [ (x,y) for x,y in lt if x < 100]

    print(lt)

    [(99, 78), (0, 32)]

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

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