【问题标题】:Sorting a list of tuples according to another list's string values [duplicate]根据另一个列表的字符串值对元组列表进行排序[重复]
【发布时间】:2019-05-28 15:05:32
【问题描述】:

我正在尝试根据另一个基于金融代码的列表对金融数据列表进行排序。

我拥有的两个列表是包含有关公司财务数据信息的元组列表。 prc_list 是具有(company_ticker, price_dataframe) 形式元素的元组列表,fin_list 是具有(company_ticker, financial_dataframe, value) 形式元素的元组列表。在这里,“价格”仅指开盘/收盘价,“财务”指您在进行基本面分析时通常会看到的信息(例如 ROE、ROA 等)

我要做的是首先获取fin_list 并根据特定的季度和键按降序对其进行排序。例如,如果我想按照 2013-Q3 的 ROE 对所有公司进行排序,那么第一家公司将显示 2013 年第三季度 ROE 值最高的公司的相关信息。

做完这个操作后,我想对prc_list进行排序,使代码的顺序与fin_list的顺序一致。

我的尝试如下:

prc_list = sorted(prc_list, key=(lambda x: fin_list[x][0]))
# Error -> "List indices must be integers or slices, not tuples."

tic_list = [fin_list[i][0] for i in range(len(fin_list))]
prc_list = sorted(prc_list, key=tic_list)
# Same error.

如何解决这个问题?

【问题讨论】:

    标签: python sorting tuples


    【解决方案1】:

    这个呢?

    fin_list = [("ticker 1" , "price 1", 10),
                ("ticker 2" , "price 2", 0),
                ("ticker 3" , "price 3", 20),
                ("ticker 4" , "price 4", 14)]
    
    # sort this list
    fin_list_sorted = sorted(fin_list, key=lambda x: x[2])
    print(fin_list_sorted)
    
    # if you want to sort it in decreasing order
    fin_list_sorted = sorted(fin_list, key=lambda x: -x[2])
    print(fin_list_sorted)
    
    # if you only want the attributes company_ticker and price_dataframe
    prc_list = list(map(lambda x: x[0:2], fin_list_sorted))
    print(prc_list)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-17
      • 2013-09-12
      • 2018-01-03
      • 2022-01-18
      • 2020-09-08
      • 1970-01-01
      • 2018-09-15
      相关资源
      最近更新 更多