【问题标题】:Finding minimum in the second column of the tuple in a nested list with integer and tuples在具有整数和元组的嵌套列表中查找元组的第二列中的最小值
【发布时间】:2021-03-14 01:43:45
【问题描述】:

我有一个整数和元组的嵌套列表:

orders = [[1, ('5464', 49.96), ('8274', 233.82), ('9744', 404.55)]
          [2, ('5464', 99.91), ('9744', 404.55)]
          [3, ('5464', 99.91), ('88112', 274.89)]
          [4, ('8732', 93.93), ('7733', 208.89), ('88112', 199.75)]]

我想得到最小值(输出):

[(1, '5464')
 (2, '5464')
 (3, '5464')
 (4, '8732')]

如何仅使用列表推导(无循环和其他函数)获得输出?

My try:
p = [[x if type(x) != tuple else min(y[1:])[1] for x in y] for y in orders]
print(p)

output:
[[1, 49.96, 49.96, 49.96], [2, 99.91, 99.91], [3, 99.91, 99.91], [4, 208.89, 208.89, 208.89]]

【问题讨论】:

    标签: python-3.x tuples list-comprehension nested-lists minimum


    【解决方案1】:

    我们可以使用切片将每个内部列表中的第一个元素与其余元素分开。请注意,orders 的每个元素都是 list,因此不需要进行类型检查。我们可以使用切片将第一个元素与其余元素分开,因为第一个元素是不同的。

    因此,在列表推导中,我们输出一个元组,其中,对于 orders 中包含的每个列表 lst,我们

    • 使用lst[0] 作为我们元组中的第一个元素
    • lst 其余部分的min(lst[1:])(当然,如果您愿意,可以在此处使用自定义key)。这将产生一个像 ('5464', 49.96) 这样的 2 元组
      • 取其中的[0]th 元素,在本例中为'5464'

    这会产生您正在寻找的输出:

    orders = [
        [1, ('5464', 49.96), ('8274', 233.82), ('9744', 404.55)],
        [2, ('5464', 99.91), ('9744', 404.55)],
        [3, ('5464', 99.91), ('88112', 274.89)],
        [4, ('8732', 93.93), ('7733', 208.89), ('88112', 199.75)],
    ]
    output = [(lst[0], min(lst[1:])[0]) for lst in orders]
    print(output)
    # [(1, '5464'), (2, '5464'), (3, '5464'), (4, '7733')]
    

    【讨论】:

    • 嗨,4 的输出不是预期的输出。
    • 为什么,第四个元素是最大值而不是最小值?列表理解看起来不错。
    • 我得到了打印正确的第四个元素的解决方案,outplut = [(lst[0], min(lst[1:], key=lambda x:x[1])[0])对于订单中的第一名]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多