I just wanted the negative values in my sublist by filtering out all the positive values.
But I am facing the TypeError: 'float' object is not iterable
or sometimes
TypeError: 'numpy.float64' object is not iterable
. ( when there's array to integrate over ),
How to solve this issue ?
My attempt :-
A = [ [-0.234, -0.435, -0.333, 0.999, 0.432, 0.995], [-0.411, -0.205, -0.505, 0.605, 0.705, 0.505], [-0.468, -0.555, -0.343, 0.977, 0.477, 0.777], [-0.244, -0.478, -0.384, 0.931, 0.405, 0.782] ]
Negative_values = []
for i in A:
for m in i:
List_of_Negative_values = list(filter(lambda x: x <= 0, m))
Negative_values.append(List_of_Negative_values)
print('Negative_values',Negative_values)
desired result
A = [ [-0.234, -0.435, -0.333], [-0.411, -0.205, -0.505], [-0.468, -0.555, -0.343], [-0.244, -0.478, -0.384] ]
CodePudding user response:
Because m
is float, but filter
requests an iterator.
Try this:
Negative_values = [ list(filter(lambda x: x <= 0, sublist)) for sublist in A ]
CodePudding user response:
try this:
[[i for i in value if i<0]for value in A]
CodePudding user response:
Here basically we going inside list via two loops and check if number is smaller then zero, if yes then take number or return None. Finally we are filter the None values using filter function.
Code:
[(lambda x: list(filter(None,[num if num<0 else None for num in x])))(x) for x in A]
Output:
[[-0.234, -0.435, -0.333],
[-0.411, -0.205, -0.505],
[-0.468, -0.555, -0.343],
[-0.244, -0.478, -0.384]]
CodePudding user response:
If you want to do this in situ then:
A = [ [-0.234, -0.435, -0.333, 0.999, 0.432, 0.995], [-0.411, -0.205, -0.505, 0.605, 0.705, 0.505], [-0.468, -0.555, -0.343, 0.977, 0.477, 0.777], [-0.244, -0.478, -0.384, 0.931, 0.405, 0.782] ]
A[:] = [[v for v in e if v < 0] for e in A]
print(A)
Otherwise, if you want a new list then:
B = [[v for v in e if v < 0] for e in A]
Output:
[[-0.234, -0.435, -0.333], [-0.411, -0.205, -0.505], [-0.468, -0.555, -0.343], [-0.244, -0.478, -0.384]]
Note:
For this particular case this is significantly faster than filter
CodePudding user response:
A = [ [-0.234, -0.435, -0.333, 0.999, 0.432, 0.995], [-0.411, -0.205, -0.505, 0.605, 0.705, 0.505], [-0.468, -0.555, -0.343, 0.977, 0.477, 0.777], [-0.244, -0.478, -0.384, 0.931, 0.405, 0.782] ]
#there no need of double loop filter run through lists
Negative_values = []
for i in A:
my_list = list(filter(lambda x: x<0, i))
Negative_values.append(my_list)
print('Negative_values',Negative_values)
Out[]:
Negative_values [[-0.234, -0.435, -0.333], [-0.411, -0.205, -0.505], [-0.468, -0.555, -0.343], [-0.244, -0.478, -0.384]]