Reputation: 323
I have a list T = [[2,5],[4,7],[8,6],[34,74],[32,35],[24,7],[12,5],[0,34]]
, and i want to check if all elements in each embedded list within T satisfy an inequality.
So far i have:
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'
So if all elements in each T[n] are between 0 and 10, i want to do something and if else then i want to do something else. In the list above T[0],T[1] and T[2] would satisfy the inequality whereas T[3] would not.
Upvotes: 2
Views: 6668
Reputation: 143
Yes, I'd also go for 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
Upvotes: 1
Reputation: 58895
I would avoid complicated code and go for 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)
Which you can reuse as a list calling test.any(axis=1).tolist()
.
Upvotes: 2
Reputation: 117380
you can also get list of indexes and checked condition with list comprehension:
>>> 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)]
Upvotes: 0
Reputation: 34493
You are almost there. Just replace range(len(T))
with T
to iterate over the T
list and check for the nested elements in the if condition, as follows :
>>> 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]
Upvotes: 6