Python 2.7:根据超过一个条件从列表中删除元组
Python 2.7: Removing tuples from a list by value basis more than one condition
假设我有一个如下格式的列表:
[(99.0,0.14),(101.0,0.11),(104.0,4.5),(78.0,14.0)]
我想遍历浮点值列表,检查元组的第一个索引中的值是否大于 100 以及元组的第二个索引中的值是否大于 10,如果是上述条件为真,随后从列表中完全删除元组。
为了得到这样的东西:
[(99.0,0.14)]
我从@StefanPochmann 对这个问题的前一个版本的回答中尝试了这个:
z = [t for t in z if t[0] <= 100 and t[1] <= 10]
但是 returns 这个错误是因为我正在处理列表元组中的浮点值:
TypeError: 'float' object is not iterable
执行此检查的最佳方法是什么?
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)]
列表理解,保留好的元组。
>>> tuples = [(99,78),(101,46),(104,69),(0,32)]
>>> [t for t in tuples if max(t) <= 100]
[(99, 78), (0, 32)]
顺便说一句,它不是元组而是列表。
编辑:这是对原始问题的回答,而不是当前的答案无效更改。
基于上面的解决方案:
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)
调用 max 和 min 没有任何作用:您一次只能使用一个值。摆脱那些。
z = [t for t in z if t[0] <= 100 and t[1] <= 10]
假设我有一个如下格式的列表:
[(99.0,0.14),(101.0,0.11),(104.0,4.5),(78.0,14.0)]
我想遍历浮点值列表,检查元组的第一个索引中的值是否大于 100 以及元组的第二个索引中的值是否大于 10,如果是上述条件为真,随后从列表中完全删除元组。
为了得到这样的东西:
[(99.0,0.14)]
我从@StefanPochmann 对这个问题的前一个版本的回答中尝试了这个:
z = [t for t in z if t[0] <= 100 and t[1] <= 10]
但是 returns 这个错误是因为我正在处理列表元组中的浮点值:
TypeError: 'float' object is not iterable
执行此检查的最佳方法是什么?
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)]
列表理解,保留好的元组。
>>> tuples = [(99,78),(101,46),(104,69),(0,32)]
>>> [t for t in tuples if max(t) <= 100]
[(99, 78), (0, 32)]
顺便说一句,它不是元组而是列表。
编辑:这是对原始问题的回答,而不是当前的答案无效更改。
基于上面的解决方案:
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)
调用 max 和 min 没有任何作用:您一次只能使用一个值。摆脱那些。
z = [t for t in z if t[0] <= 100 and t[1] <= 10]