0

我正在尝试实现一个元组,我最终将作为批量更新上传到 PostgreSQL 数据库。如果我错了,或者是否有更好的方法来实现我的目标,请告诉我。

我的代码如下:


index = []
n = -1
for stock in stocklist[0:2000]:
    n += 1
    time.sleep(1)

    # RS_Rating code begins here
    data = get_history(stock, start=start_date, end=end_date)

    if not data.empty:
        row_count = 0
        day_prices = []
        for row in data.itertuples():
            row_data = "("  + str(row.Index) + ", '" + row.Symbol + "', " + str(row.Open) + ", " + str(row.High) + ", " + str(row.Low) + ", " + str(row.Last) + ')'
            
            if day_prices==[]:
                day_prices = row_data
            else:
                day_prices = day_prices + ", "+  row_data

            row_count = row_count + 1 # TO MAKE IT EASIER FOR TESTING WITH LIMITED CODE
            if row_count == 5:
                break

        # type(day_prices)
        # <class 'str'>
        
        day_prices_post = day_prices

        # WHAT I AM GETTING IS AS BELOW. 
        # ALL PERFECT BUT I NEED TO GET RID OF THE QUOTES " ... "

        day_prices_post = "(
            ('SBIN', 198.50, 202.50),
            ('RELIANCE', 1910.50, 1930.50),
            ('RELIANCE', 1925.60, 1933.00)
        )"
        
        # I NEED A TUPLE IN THIS LAYOUT
        # SIMILAR TO ABOVE BUT WITHOUT QUOTES " ... "
        day_prices_test = (
            ('SBIN', 198.50, 202.50),
            ('RELIANCE', 1910.50, 1930.50),
            ('RELIANCE', 1925.60, 1933.00)
        )
        
        # type(day_prices_test)
        # <class 'tuple'>
4

1 回答 1

1

您不需要以字符串开头。对于每一行,您可以根据需要创建一个元组,然后将其添加到列表中。最后,您可以使用 tuple 函数将列表转换为元组:

index = []
n = -1
for stock in stocklist[0:2000]:
    n += 1
    time.sleep(1)

    # RS_Rating code begins here
    data = get_history(stock, start=start_date, end=end_date)

    if not data.empty:
        row_count = 0
        day_prices = []
        for row in data.itertuples():
            row_data = (row.Index , row.Symbol , row.Open , row.High, row.Low, row.Last)            
            day_prices.append(row_data)
            row_count += 1 # TO MAKE IT EASIER FOR TESTING WITH LIMITED CODE
            if row_count == 5:
                break
        day_prices = tuple(day_prices)
        # type(day_prices)
        # <class 'tuple'>
        

于 2020-11-03T08:21:40.903 回答