【问题标题】:Stacking/concatenated arrays and "None"?堆叠/连接数组和“无”?
【发布时间】:2014-06-20 08:28:30
【问题描述】:

我有一些代码:

# first round
curr_g = np.array([])
temp_g = np.array([1,2,3])

if curr_g is not None:
    curr_g = temp_g
    print "in is not none"
else:
    curr_g = np.c_[curr_g, temp_g]
    print "in is none"

print "curr_g: "
print curr_g

#second round
temp_g = np.array([4,5,6]) 
if curr_g is not None:
    print "in is not none"
    curr_g = temp_g
else:
    print "in none"
    curr_g = np.c_[curr_g, temp_g]

print "curr_g: "
print curr_g

上面的输出如下:

in is not none
curr_g: 
[1 2 3]
in is not none
curr_g: 
[4 5 6]

到底为什么这个条件两次都变成“不是没有”? curr_g 在被分配temp_g 之后,在第二轮中只是“not None”。

我的目标是在第一轮中,因为curr_g 是真正的空,它应该填充temp_g,第二次,它实际上应该连接到temp_g 并变成如下:

[
1  4
2  5
3  6
]

我该怎么做?

【问题讨论】:

    标签: python arrays numpy stack concatenation


    【解决方案1】:

    “空”与None 不同。 None 是一个特定的对象,它与您的(或任何)numpy 数组不同,因此您的数组不是None

    如果您想检查您的数组是否为空,只需执行if curr_g。也就是说,如果您要做的只是用其他东西覆盖它,那么为curr_g 创建一个空数组没有多大意义。您可以使用curr_g = None 对其进行初始化,然后您的is None 检查将起作用。

    【讨论】:

      【解决方案2】:

      如果你想检查None,你应该明确指定None

      curr_g = None
      

      正如 BrenBarn 提到的,您分配了一个空的 numpy 数组,它不等于 None,而不是一个空的 python 列表。

      【讨论】:

        猜你喜欢
        • 2021-07-07
        • 1970-01-01
        • 2014-06-20
        • 1970-01-01
        • 2017-07-14
        • 2019-09-27
        • 1970-01-01
        • 1970-01-01
        • 2018-06-19
        相关资源
        最近更新 更多