我在 Python 中有两种算法,它们将元组列表转换为字典:
  def _prep_high_low_data_for_view(self, low_high_list):
    dates = []
    prices = []
    lables = []
    for (x, y, z) in low_high_list:
        dates.append(x)
        prices.append(y)
        lables.append(z)
    return {'date': dates,
            'price': prices,
            'label': lables
            }
Run Code Online (Sandbox Code Playgroud)
第二个是:
    def _prep_high_low_data_for_view(self, low_high_list):
    return {'date': [date for date, _, _ in low_high_list],
            'price': [price for _, price, _ in low_high_list],
            'label': [lable for _, _, lable in low_high_list],
            }
Run Code Online (Sandbox Code Playgroud)
两种算法就它们的作用而言是等效的。是不是第二种算法在复杂度方面更差,因为有三个单独的列表推导式?
您可以使用 zip 构建 3 个列表:
dates,prices,labels = zip(*low_high_list)
Run Code Online (Sandbox Code Playgroud)
放在一个单行函数中:
def third_function(low_high_list):
    return dict.fromkeys(zip(["date","price","label"],zip(*low_high_list)))
Run Code Online (Sandbox Code Playgroud)
平均而言,它会比 Florian_H 的 second_function() 运行得更快。
测试和结果:
def third_function(low_high_list):
    return dict.fromkeys(zip(["date","price","label"],zip(*low_high_list)))
def fourth_function(low_high_list):
    dates,prices,labels = zip(*low_high_list)
    return { "date":dates, "price":prices, "label":labels }
lst = [tuple(random.randint(0,100) for _ in range(3)) for i in range(10000)]
from timeit import timeit
count = 1000
t0 = timeit(lambda:first_function(lst), number=count)
print("first_function: ",f"{t0:.3f}","1x" )
t = timeit(lambda:second_function(lst), number=count)
print("second_function:",f"{t:.3f}",f"{t0/t:.1f}x" )
t = timeit(lambda:third_function(lst), number=count)
print("third_function: ",f"{t:.3f}",f"{t0/t:.1f}x" )
t = timeit(lambda:fourth_function(lst), number=count)
print("fourth_function:",f"{t:.3f}",f"{t0/t:.1f}x" )
# first_function:  1.338 1x
# second_function: 0.818 1.6x
# third_function:  0.426 3.1x
# fourth_function: 0.375 3.6x
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           838 次  |  
        
|   最近记录:  |