简体   繁体   English

如何使用变量列表循环 function?

[英]How to loop function using a list of variables?

I have a function that prints OHLCV data for stock prices from a websocket.我有一个 function 打印来自 websocket 的股票价格的 OHLCV 数据。 It works but I have to copy it for each variable (Var1 to Var14) to get each individual stock data.它有效,但我必须为每个变量(Var1 到 Var14)复制它以获取每个单独的股票数据。 How would I automate this process given that I have list:鉴于我有列表,我将如何自动化这个过程:

varlist = [var1, var2, var3...var14]

and my code is:我的代码是:

def process_messages_for_var1(msg):
    if msg['e'] == 'error':
        print(msg['m'])
   # If message is a trade, print the OHLC data
    else:
    # Convert time into understandable structure
    transactiontime = msg['k']['T'] / 1000
    transactiontime = datetime.fromtimestamp(transactiontime).strftime('%d %b %Y %H:%M:%S')
    # Process this message once websocket starts
    print("{} - {} - Interval {} - Open: {} - Close: {} - High: {} - Low: {} - Volume: {}".
          format(transactiontime,msg['s'],msg['k']['i'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v']))
    # Also, put information into an array
    kline_array_msg = "{},{},{},{},{},{}".format(
        msg['k']['T'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v'])         
# Insert at first position
    kline_array_dct[var1].insert(0, kline_array_msg)
    if (len(kline_array_dct[var1]) > window): 
        # Remove last message when res_array size is > of FIXED_SIZE
        del kline_array_dct[var1][-1]

I'm hoping to get the following result (notice how function name also changes):我希望得到以下结果(注意 function 名称也发生了变化):

def process_messages_for_var2(msg):
   if msg['e'] == 'error':
       print(msg['m'])
   # If message is a trade, print the OHLC data
   else:
   # Convert time into understandable structure
   transactiontime = msg['k']['T'] / 1000
   transactiontime = datetime.fromtimestamp(transactiontime).strftime('%d %b %Y %H:%M:%S')
   # Process this message once websocket starts
   print("{} - {} - Interval {} - Open: {} - Close: {} - High: {} - Low: {} - Volume: {}".
          format(transactiontime,msg['s'],msg['k']['i'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v']))
    # Also, put information into an array
    kline_array_msg = "{},{},{},{},{},{}".format(
        msg['k']['T'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v'])         
# Insert at first position
    kline_array_dct[var2].insert(0, kline_array_msg)
    if (len(kline_array_dct[var2]) > window): 
        # Remove last message when res_array size is > of FIXED_SIZE
        del kline_array_dct[var2][-1]

You can adjust the function so that it takes one of the var s as an argument.您可以调整 function 使其将var之一作为参数。 Ie, IE,

def process_messages(msg, var):
    ...

    kline_array_dct[var].insert(0, kline_array_msg)
    if (len(kline_array_dct[var]) > window): 
        # Remove last message when res_array size is > of FIXED_SIZE
        del kline_array_dct[var][-1]

If the processes are generally the same, just define one of them, and give it more arguments:如果流程大体相同,只定义其中一个,多给arguments:

def process_messages(msg, var)

Then, you can adjust your process code to run through each var when you call it.然后,您可以调整您的流程代码以在调用每个 var 时运行它。 You can do this by removing the numbered vars in the process code:您可以通过删除流程代码中的编号变量来做到这一点:

if msg['e'] == 'error':
   print(msg['m'])
   # If message is a trade, print the OHLC data
   else:
   # Convert time into understandable structure
   transactiontime = msg['k']['T'] / 1000
   transactiontime = datetime.fromtimestamp(transactiontime).strftime('%d %b %Y %H:%M:%S')
   # Process this message once websocket starts
   print("{} - {} - Interval {} - Open: {} - Close: {} - High: {} - Low: {} - Volume: {}".
          format(transactiontime,msg['s'],msg['k']['i'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v']))
    # Also, put information into an array
    kline_array_msg = "{},{},{},{},{},{}".format(
        msg['k']['T'],msg['k']['o'],msg['k']['c'],msg['k']['h'],msg['k']['l'],msg['k']['v'])         
# Insert at first position
    kline_array_dct[var].insert(0, kline_array_msg)
    if (len(kline_array_dct[var]) > window): 
        # Remove last message when res_array size is > of FIXED_SIZE
        del kline_array_dct[var][-1]

Then, create a simple for loop to call the process for each var in the list:然后,创建一个简单for循环来为列表中的每个 var 调用进程:

for var in varList:
    process_messages("msg", var)

The for loop will call the process for each var in the list. for 循环将为列表中的每个 var 调用进程。

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

相关问题 使用 for 循环将 function 输出分配给列表中的变量 - Assign function outputs to variables in list using for-loop 我有一个变量列表和一个 function。 我将如何创建一个循环来让这个 function 运行这些变量? - I have a list of variables and a function. How would I create a loop to get this function to run through these variables? 如何使用带有要更改的变量的列表在 for 循环中更改分类变量 - How to change categorical variables in a for loop using a list with variable to change 如何在python中使用函数和循环调用变量 - how to call the variables using function together with loop in python 如果我使用for循环生成字符串列表,那么如何创建变量列表而不是字符串列表? - If I'm using a for loop to generate a list of strings, how do I create a list of the variables, and not a list of the strings? 如何在不使用全局变量的情况下从函数添加2个列表? - How to add 2 list from a function without using global variables? Python - 在循环中使用预定义变量列表(psychopy) - Python - Using a list of predefined variables in a loop (psychopy) 在循环中使用字符串形式的列表作为变量 - Using strings form list inside a loop as variables 使用循环将值分配给变量列表 - Assign a value to a list of variables using a loop 使用循环将值分配给列表中的变量 - Assigning values to variables in a list using a loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM