简体   繁体   English

for循环仅打印实时市场中dict的最后一个值

[英]for loop print only last value from dict in live market

try to print LTP data for more than one crypto in live market but printing only for one crypto.尝试在实时市场中打印多个加密货币的 LTP 数据,但仅打印一种加密货币。

import pandas as pd
import requests
import json

ltp_data= []

crypto = {"BTCUSDT",  "LTCUSDT", "DOGEUSDT"}
def live_ltp():
    for i in crypto:
        key = "https://api.binance.com/api/v3/ticker/price?symbol="
        url = key+i
        response = requests.get(url)
        Ltp = response.json()
        ltp_data.append(Ltp)
        return Ltp
while True:
    print(str(live_ltp())) 

return will exit your loop as soon as it is hit. return 一旦被击中就会退出你的循环。 If you bring your return statement outside of the loop, and have it return ltp_data (instead of the "LTP" json object) you should be able to get the items in the list you appear to be populating.如果您将 return 语句带出循环,并让它返回 ltp_data (而不是“LTP”json 对象),您应该能够获得您似乎正在填充的列表中的项目。

ltp_data= []

crypto = {"BTCUSDT",  "LTCUSDT", "DOGEUSDT"}
def live_ltp():
    for i in crypto:
        key = "https://api.binance.com/api/v3/ticker/price?symbol="
        url = key+i
        response = requests.get(url)
        Ltp = response.json()
        ltp_data.append(Ltp)
    return ltp_data

crypto_ltps = live_ltp()
print(crypto_ltps)

You have a return Ltp in the for loop so you will always just get a single response for the first item in the set of crypto id's.您在for循环中有一个return Ltp ,因此您将始终只获得一组加密 id 中第一项的单个响应。 You could instead do return lpd_data after the loop ends.您可以在循环结束return lpd_data But that creates a new problem - since you are updating a global list, it will just keep growing and growing.但这产生了一个新问题——因为你正在更新一个全局列表,它只会不断增长。

Instead, write your function to take input parameters and return a locally-generated list.相反,编写您的 function 以获取输入参数并返回本地生成的列表。

import pandas as pd
import requests
import json

def live_ltp(crypto_ids):
    ltp_data = []
    for i in crypto_ids:
        key = "https://api.binance.com/api/v3/ticker/price?symbol="
        url = key+i
        response = requests.get(url)
        Ltp = response.json()
        ltp_data.append(Ltp)
    return ltp_data

crypto = {"BTCUSDT",  "LTCUSDT", "DOGEUSDT"}

while True:
    print(str(live_ltp(crypto))) 

You have added the return statement at the end of loop because of which it's executing only one time and returning only 1 data.您在循环末尾添加了 return 语句,因为它只执行一次并且只返回 1 个数据。

Instead,反而,

import pandas as pd
import requests
import json

ltp_data= []

crypto = {"BTCUSDT",  "LTCUSDT", "DOGEUSDT"}
def live_ltp():
    responses = []
    for i in crypto:
        key = "https://api.binance.com/api/v3/ticker/price?symbol="
        url = key+i
        response = requests.get(url)
        Ltp = response.json()
        ltp_data.append(Ltp)
        responses.append(Ltp)
    return responses
while True:
    print(str(live_ltp()))

This will solve the problem.这将解决问题。
Hope this helps you.!!希望这对你有帮助。!! Please free to comment if you get any error in this and mark the answer as correct if it worked.如果您对此有任何错误,请自由发表评论,如果有效,请将答案标记为正确。

solution with dataframe in place. dataframe 的解决方案。

you will need to pass empty dataframe to function: live_ltp(df_frame) .您需要将空的 dataframe 传递给 function: live_ltp(df_frame)

I would also use .json_normalize to set table in place properly.我还会使用.json_normalize正确设置表格。

import pandas as pd
import requests
import json


ltp_data = pd.DataFrame() # empty dataframe (not list) which will be updated in the function below
crypto = {"BTCUSDT",  "LTCUSDT", "DOGEUSDT"}

def live_ltp(df_frame):
    for i in crypto:
        key = "https://api.binance.com/api/v3/ticker/price?symbol="
        url = key+i
        response = requests.get(url)
        Ltp = response.json()
        ltp_df = pd.json_normalize(Ltp)
        ltp_df['time'] = pd.Timestamp.now()
        df_frame = pd.concat([df_frame, ltp_df], axis=0)
    return df_frame


while True:
    final_df = live_ltp(ltp_data) # passing empty dataframe to function
    final_df.to_excel('test.xlsx', index=False)
    print(final_df)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM