【问题标题】:Changing array string inputs to integer inputs not working将数组字符串输入更改为整数输入不起作用
【发布时间】:2021-09-14 18:30:43
【问题描述】:

对于 Cryptotrading 的项目,我正在尝试制作自己的扫描仪。首先,我收集数据并将它们附加到列表中。然后我将列表转换为 np.array。然后该数组将字符串作为输入,但我需要将它们更改为整数。当我打印 np_closelist 时,它会给出所有所需的值,但在一个带有字符串的数组中。当我尝试打印 b (因此将 np_closelist 转换为整数)时,它不会打印任何内容。当我在具有简单值的不同文件中尝试此方法时,它确实有效。谁能帮我弄清楚如何解决这个问题? 提前致谢!

import numpy as np
import talib
import websocket, json, pprint

socket = "wss://stream.binance.com:9443/ws/btcusdt@kline_1m"


closelist = []

def on_open(ws):
    print('open')
            
def on_close(ws):
    print('close')
    
def on_message(ws, message):
    global closelist
    json_message = json.loads(message)
 #   pprint.pprint(json_message)
    candle = json_message['k']
    is_candle_closed = candle['x']
    close = candle['c']
    high = candle['h']
    low = candle['l']
    
    if is_candle_closed:

        closelist.append(format(float(close)))
        
        closelist.append(format(float(high)))
        
        closelist.append(format(float(low)))
        np_closelist = np.array(closelist)
         
        b = np.array([int(i) for i in np_closelist])
        print(b)
        print(type(b))
        print(type(b[1]))

ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message, on_close=on_close)
ws.run_forever()

【问题讨论】:

    标签: python cryptocurrency


    【解决方案1】:

    为什么将浮点数格式化为字符串? 如果您执行以下操作:

        
        if is_candle_closed:
    
            closelist.append(float(close))
            
            closelist.append(float(high))
            
            closelist.append(float(low))
            np_closelist = np.array(closelist)
             
            b = np.array([int(i) for i in np_closelist])
            print(b)
            print(type(b))
            print(type(b[1]))
    
    

    它应该会产生预期的结果。如果你先用一个浮点数将浮点数包裹在里面,它也应该可以工作,比如

    b = np.array([int(float(i)) for i in np_closelist])
    

    问题在于尝试将浮点字符串对象直接转换为 int,这通常会引发类似的错误

    ValueError: invalid literal for int() with base 10: '3.0'
    

    【讨论】:

    • 您好,谢谢您的回答!嗯,我对编程还是有点陌生​​,所以我真的不明白你为什么将浮点数更改为字符串的意思。我将数字转换为浮点数,然后将它们附加到列表(closelist)中。在哪里将浮点数转换为字符串?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2013-01-31
    • 2016-06-19
    相关资源
    最近更新 更多