代码之家  ›  专栏  ›  技术社区  ›  PineNuts0

在较大的列表中处理一组列表并使用Lambda函数

  •  -1
  • PineNuts0  · 技术社区  · 4 年前

    我有以下列表:

    list_of_lists = [['43', 'Yellowjackets', '98.6'], ['10', 'Book of Bobba Fett', '32.245'], ['132', 'And Just Like That', '77.014'], ['2', 'Sex & The City', '4.732']]
    

    我想将每个单独列表的第三个元素(index=2)从字符串更改为浮点值。例如,在第一个列表中,我想要['43','Yellowjackets', 98.6 ]

    但这是棘手的部分。。。我想在sort()函数中将字符串更改为浮动。我当前的排序函数为:

    list_of_lists .sort(key=float(lambda x:x[2]))
    

    但我得到以下错误: enter image description here

    1 回复  |  直到 4 年前
        1
  •  1
  •   user7864386 user7864386    4 年前

    如果您想在排序前更改第三个元素的类型,那么您可以使用列表理解,然后进行排序。

    list_of_lists[:] = [sublist[:2] + [float(sublist[2])] for sublist in list_of_lists]
    list_of_lists.sort(key=lambda x:x[2])
    print(list_of_lists)
    

    输出:

    [['2', 'Sex & The City', 4.732],
     ['10', 'Book of Bobba Fett', 32.245],
     ['132', 'And Just Like That', 77.014],
     ['43', 'Yellowjackets', 98.6]]
    

    但如果你只想 sort 方法将第三个元素视为浮点,然后可以使用 float lambda中的函数:

    list_of_lists.sort(key=lambda x: float(x[2]))
    print(list_of_lists)
    

    输出:

    [['2', 'Sex & The City', '4.732'],
     ['10', 'Book of Bobba Fett', '32.245'],
     ['132', 'And Just Like That', '77.014'],
     ['43', 'Yellowjackets', '98.6']]