[英]Apply condition in for loop to each element in a list of lists
I am trying to see if each value in array is less then 0 then output 0, else output the number itself.我试图查看数组中的每个值是否小于 0,然后 output 0,否则 output 是数字本身。 The output must have the same dimensions as the input.
output 必须具有与输入相同的尺寸。 Currently the input is a 3 by 4 but output is a list.
目前输入是 3 x 4 但 output 是一个列表。 How do I get the output size the same (3 by 4 array)?
如何使 output 大小相同(3 x 4 阵列)?
input = [[1,2,3,4],[4,5,-6,-7],[8,9,10,11]]
output= []
for i in input:
if i < 0:
value = 0
output.append(value)
else:
value= i
output.append(value)
You need a nested loop.你需要一个嵌套循环。
lists = [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 10, 11]]
output = []
for l in lists:
nested_list = []
for i in l:
if i < 0:
nested_list.append(0)
else:
nested_list.append(i)
output.append(nested_list)
Also, you shouldn't name your variable input
as it will override the input()
function.此外,您不应命名变量
input
,因为它会覆盖input()
function。
Python's NumPy arrays are a much more efficient way of dealing with nested lists. Python 的NumPy arrays是处理嵌套列表的一种更有效的方法。 If I understood your question, your example can be simplified down to a single line:
如果我理解您的问题,您的示例可以简化为一行:
import numpy as np
inp = np.array([[-1,2,3,4],[4,5,-6,7],[8,9,-10,11]])
print (inp)
#[[ -1 2 3 4]
# [ 4 5 -6 7]
# [ 8 9 -10 11]]
inp[inp < 0] = 0
print (inp)
# [[ 0 2 3 4]
# [ 4 5 0 7]
# [ 8 9 0 11]]
you can achieve it this way -你可以通过这种方式实现它 -
l = [[1,2,3,4],[4,5,-6,-7],[8,9,10,11]]
res = [[x if x >= 0 else 0 for x in in_l]for in_l in l]
You don't necessarily need to import any additional libraries for this, that would be an overkill.您不一定需要为此导入任何其他库,这将是一种矫枉过正。 Base python provides all the necessary operations for handling nested data structures and conditional operations.
Base python 提供了处理嵌套数据结构和条件操作的所有必要操作。
You can do this with a combination of list comprehension and ternary operators in python -您可以在 python 中结合使用列表理解和三元运算符来做到这一点 -
inp = [[1,2,3,4],[4,5,-6,-7],[8,9,10,11]]
[[0 if item<0 else item for item in sublist] for sublist in inp]
#|____________________|
# |
# ternary operator
[[1,2,3,4],[4,5,0,0],[8,9,10,11]]
Alist comprehension would allow you to avoid the list.append()
and directly result in a list as output. 列表理解将允许您避免使用
list.append()
并直接导致列表为 output。 Note, that you need a listed list comprehension since you want to iterate over elements of a list of lists.请注意,您需要一个列出的列表理解,因为您想遍历列表列表的元素。
A ternary operator is a conditional expression of the form [on_true] if [expression] else [on_false]
.三元运算符是
[on_true] if [expression] else [on_false]
形式的条件表达式。 This lets you add conditions (if-else) to the list comprehension on each element you are iterating.这使您可以将条件(if-else)添加到您正在迭代的每个元素的列表推导中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.