通過過濾掉所有正值,我只想要子串列中的負值。
但我面臨TypeError: 'float' object is not iterable 或有時
TypeError: 'numpy.float64' object is not iterable. (當有陣列要集成時),
如何解決這個問題?
我的嘗試:-
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)
期望的結果
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] ]
uj5u.com熱心網友回復:
因為m是浮動的,但filter需要一個迭代器。
嘗試這個:
Negative_values = [ list(filter(lambda x: x <= 0, sublist)) for sublist in A ]
uj5u.com熱心網友回復:
嘗試這個:
[[i for i in value if i<0]for value in A]
uj5u.com熱心網友回復:
這里基本上我們通過兩個回圈進入串列并檢查數字是否小于零,如果是則取數字或回傳無。最后,我們使用過濾器功能過濾無值。
代碼:
[(lambda x: list(filter(None,[num if num<0 else None for num in x])))(x) for x in 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]]
uj5u.com熱心網友回復:
如果您想就地執行此操作,則:
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)
否則,如果你想要一個新串列,那么:
B = [[v for v in e if v < 0] for e in 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]]
筆記:
對于這種特殊情況,這比過濾器快得多
uj5u.com熱心網友回復:
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]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/511142.html
下一篇:將串列轉換為小寫
