繁体   English   中英

Python - 检查列表中的所有元素是否满足不等式

[英]Python - Check if all elements in a list satisfy an inequality

我有一个列表T = [[2,5],[4,7],[8,6],[34,74],[32,35],[24,7],[12,5],[0,34]] ,我想检查T中每个嵌入列表中的所有元素是否满足不等式。

到目前为止,我有:

upper = 10
lower = 0
for n in range(len(T)):
    if all(lower < x < upper for x in T):
        'do something'
    else:
        'do something different'

因此,如果每个T [n]中的所有元素都在0到10之间,我想做某事,如果不然,那么我想做其他事情。 在上面的列表T [0]中,T [1]和T [2]将满足不等式,而T [3]则不满足。

你快到了。 只需更换range(len(T))T遍历T列表,并检查在如果条件的嵌套元素,如下:

>>> T = [[2,5],[4,7],[8,6],[34,74],[32,35],[24,7],[12,5],[0,34]]
>>> upper = 10
>>> lower = 0
>>> for elem in T:
        if all(lower < x < upper for x in elem):
            print "True", elem
        else:
            print "False", elem


True [2, 5]
True [4, 7]
True [8, 6]
False [34, 74]
False [32, 35]
False [24, 7]
False [12, 5]
False [0, 34]

我会避免复杂的代码,并采取numpy

a = np.array(T)

test = (a>0) & (a<10)
#array([[ True,  True],
#       [ True,  True],
#       [ True,  True],
#       [False, False],
#       [False, False],
#       [False,  True],
#       [False,  True],
#       [False, False]], dtype=bool)

test.all(axis=1)
#array([ True,  True,  True, False, False, False, False, False], dtype=bool)

您可以将其重用为调用test.any(axis=1).tolist()

是的,我也会选择numpy:

import numpy as np

T = [[2,5],[4,7],[8,6],[34,74],[32,35],[24,7],[12,5],[0,34]]
T = np.array(T)
for t in T:
    if np.all(t>0) & np.all(t<10):
        print t
    else:
        print 'none'

[2 5]
[4 7]
[8 6]
none
none
none
none
none

您还可以使用列表解析获取索引列表和已检查条件:

>>> T = [[2,5],[4,7],[8,6],[34,74],[32,35],[24,7],[12,5],[0,34]]
>>> upper = 10
>>> lower = 0
>>> result = [(i, all(lower < x < upper for x in l)) for i, l in enumerate(T)]
[(0, True), (1, True), (2, True), (3, False), (4, False), (5, False), (6, False), (7, False)]

暂无
暂无

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

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