[英]Modify 2D Array (Python)
Hey guys so I have a 2D array that looks like this: 大家好,我有一个二维数组,如下所示:
12381.000 63242.000 0.000 0.000 0.000 8.000 9.200 0.000 0.000
12401.000 8884.000 0.000 0.000 96.000 128.000 114.400 61.600 0.000
12606.000 74204.000 56.000 64.000 72.000 21.600 18.000 0.000 0.000
12606.000 105492.000 0.000 0.000 0.000 0.000 0.000 0.000 45.600
12606.000 112151.000 2.400 4.000 0.000 0.000 0.000 0.000 0.000
12606.000 121896.000 0.000 0.000 0.000 0.000 0.000 60.800 0.000
(Cut off couple of columns due to formatting) (由于格式化,切除了几列)
So it indicates the employee ID, Department ID, followed by the 12 months worked by each employee and the hours they worked for each month. 因此它指示员工ID,部门ID,然后是每个员工的12个月工作时间以及每个月的工作时间。 My 2D array is essentially a list of lists where each row is a list in its own. 我的2D数组本质上是一个列表列表,其中每一行都是它自己的列表。 I am trying to convert each nonzero value to a one and maintain all the zeros. 我试图将每个非零值都转换为1并保持所有零。 There are 857 rows and 14 columns. 有857行和14列。 My code is as follows: 我的代码如下:
def convBin(A):
"""Nonzero values are converted into 1s and zero values are kept constant.
"""
for i in range(len(A)):
for j in range(len(A[i])):
if A[i][j] > 0:
A[i][j] == 1
else:
A[i][j] == 0
return A
Can someone tell me what I am doing wrong? 有人可以告诉我我在做什么错吗?
You are doing equality evaluation , not assignment , inside your loop: 您正在循环内进行相等评估 ,而不是赋值 :
A[i][j] == 1
should be 应该
A[i][j] = 1
# ^ note only one equals sign
Also, there is no need to return A
; 同样,也不需要return A
; A
is being modified in-place, so it is conventional to implicitly return None
by removing the explicit return ...
line. A
是就地修改的,因此通常通过删除显式return ...
行来隐式return None
。
You should bear in mind that: 您应该记住:
else
case; 在else
情况下,您实际上不希望执行任何操作; and 和 range(len(...))
is not Pythonic - use eg enumerate
. 遍历range(len(...))
不是Python的-使用例如enumerate
。 Your function could therefore be simplified to: 因此,您的功能可以简化为:
def convBin(A):
"""Convert non-zero values in 2-D array A into 1s."""
for row in A:
for j, val in enumerate(row):
if val:
row[j] = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.