【问题标题】:How to append a single element to a new numpy array如何将单个元素附加到新的 numpy 数组
【发布时间】:2018-04-11 06:50:18
【问题描述】:

如何将单个元素(最好是浮动值)从用户输入附加到 numpy 数组。我在下面编写的代码每次只打印出一个空数组,我无法理解为什么没有附加任何内容。

import numpy as np

start=0
start_prompt = int(input("Start press 1"))
while start_prompt > start:
   x=np.array([])
   y = float(input("Please input number:  "))
   if y > 0: 
       np.append(x,y)
   print(x)

【问题讨论】:

  • 我只会使用 python 列表,这里不需要 numpy 数组。
  • 这也是一个无限循环......
  • 不要使用 np.append - 特别是没有阅读它的文档。
  • @roganjosh 是正确的。追加到列表比追加到数组要快得多。如果您真的想使用数组预分配元素,请参阅我在这里整理的一些粗略基准:stackoverflow.com/questions/46860970/…

标签: python arrays numpy append


【解决方案1】:

你必须改变你的阵列,对吧?你必须把它写成:

x = np.append(x, y)

>>> while start_prompt > start:
...     x=np.array([])
...     y = float(input("Please input number:  "))
...     if y > 0: 
...         x = np.append(x, y)
...     print(x)

另外,首先你正在运行一个无限循环,因为 start_prompt 总是大于 start。您在循环中创建了 x 数组,它将在每次迭代时重新初始化。如果您希望它按预期工作,请在 while 循环之外声明它。其次,有很多更好的方法来做你想做的事情。

【讨论】:

  • 您需要将x=np.array([]) 移出循环。
  • 我知道这是一个无限循环,但 x 的值仍然会改变。
  • @pissall 但您通过在循环的每次迭代中将数组重新定义为空数组来继续撤消您的工作。您的代码没有有意义的输出。
  • 我对您的回答的评论与无限循环无关。你不断将x 初始化为一个空数组
  • 我知道。但是你忘记了问的问题。上下文是,为什么他的数组没有改变。我已经回答了。否则发生的一切与我无关。
【解决方案2】:

大家好,感谢您的回复。我已经接受了您的建议,并对所有建议进行了一些试验和错误,并使其按照我的预期工作,非常感谢所有评论者。这是有效的代码(希望在复制和粘贴过程中没有错误)

def get_user_values1(x):
    x = np.array([])
    initial = float(input("Input the cup weight in grams:"))
    while initial <= 0:
        #print ("Invalid")
        initial = float(input("Input the cup weight in grams:"))
        x=np.append(x,initial)
    else:
        x=np.append(x,initial)
    return (x)



def main():
    x = np.array([])
    start = 1 #1 = yes stasrt script
    start_prompt = int(input("To start press 1, To Close press 0: "))
    while start_prompt == start:    
        get_user1 = get_user_values1 (x)
        x = np.append(x,get_user1)




main()

【讨论】:

    猜你喜欢
    • 2020-07-07
    • 2021-09-16
    • 2020-06-03
    • 1970-01-01
    • 2011-11-12
    • 2017-03-03
    • 2017-05-22
    • 1970-01-01
    • 2012-08-30
    相关资源
    最近更新 更多