如何将python类'str'转换为类'tuple'而无需使用引号引起来

问题描述

我正在尝试实现一个元组,最终将其作为批量更新上传到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),1925.60,1933.00)
        )"
        
        # I NEED A TUPLE IN THIS LAYOUT
        # SIMILAR TO ABOVE BUT WITHOUT QUOTES " ... "
        day_prices_test = (
            ('SBIN',1933.00)
        )
        
        # type(day_prices_test)
        # <class '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'>