【问题标题】:Passing an array list of string to function in Python将字符串的数组列表传递给Python中的函数
【发布时间】:2020-07-06 16:45:52
【问题描述】:

我是 Python 的初学者,我正在尝试编写一个函数。

对于符号,我有一个从数据库中获取的列表

cur.execute("SELECT sym FROM data")

list = cur.fetchall()              ####fetches list from database column

 

[['AAPL']                       ####This is the output of list
 ['MSFT']
 ['GOOGL']
 ['TSLA']
 ['AMZN']
 ['FB']
 ['V']
 ['BABA']
 ['WMT']]

如何在 symbol 中为以下函数传递此列表的值?

    symbol = 
    url_cf = 'https://somewebsite.com' + symbol

    def scrape_data():
        def dir_create():
            # base dir
            _dir = "/Users/Desktop/Companies"
    
            # create dynamic name
            _dir2 = os.path.join(_dir, symbol)
    
            # create 'dynamic' dir, if it does not exist
            if not os.path.exists(_dir2):
                os.makedirs(_dir2)
    
    
        dir_create()
    
    
        # Scraping Cash Flow
        def cash_flow():
        .
        .
        page = requests.get(url_cf, headers)
        .
        .
        #### Some function for scraping
        .
        .
        path = '/Users/Desktop/Companies' + '/' + symbol
        sheet_name = str('cash_flow_' + symbol + '.xlsx')
        .
        .
        cash_flow()

scrape_data()

我希望对列表中的每个符号执行 scrape_data()。

【问题讨论】:

    标签: python python-3.x list function web-scraping


    【解决方案1】:

    如果我正确理解了您的问题,您可以像这样简单地将列表传递给函数:

    def scrape_data(symbol):
        #...
    
    scrape_data(symbol)
    

    在这种情况下,重要的是要说,symbol 是一个列表,您必须在函数内部循环遍历它们。 但是,如果您想为symbol 中的每个值运行该函数,您应该这样做:

    def scrape_data(symbol):
        #...
    
    for symb in symbol:
        scrape_data(symb)
    

    在这种情况下,该函数将从列表symbol 中一一获取元素。

    另外,请重命名您的列表。您对函数外部的列表和函数内部的字符串使用相同的名称。

    【讨论】:

      【解决方案2】:

      使用参数和循环:

      def scrape_data(symbol):
          url_cf = f'https://somewebsite.com/{symbol}'
          ....
      
      
      for sym, in list:
          scrape_data(sym)
      

      在 Python3 中,您可以使用 f-strings 使变量连接更容易 请注意for 循环声明中sym 之后的,。这将解压缩列表中的列表元素。如果每行有多个值,这将失败,考虑到您的数据库查询,这不应该发生

      【讨论】:

        猜你喜欢
        • 2016-12-08
        • 1970-01-01
        • 2011-04-27
        • 2021-05-31
        • 2015-09-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多