python列表理解以获取每个列表列的最大值()

发布于 2025-02-12 21:26:06 字数 192 浏览 1 评论 0原文

我有以下列表的列表:

lst = [[1,3], [3,4], [2,7], [6,5]]

如何创建“ Oneliner”以获取每个“列”的Max()列表?

因此,对于上面的示例,结果列表应如下:[6,7],其中6是“ 0列”的最大值,而7是“第1列”的最大值。

I have following list of lists:

lst = [[1,3], [3,4], [2,7], [6,5]]

How do I create "oneliner" to get list of max() of each "column"?

So, for the example above, the resulting list should be following: [6,7], where 6 is the maximum of "column 0" and 7 is the maximum of "column 1".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倦话 2025-02-19 21:26:07

您可以使用 zip < < /a>将对分成两个单独的元组:

>>> lst = [[1,3], [3,4], [2,7], [6,5]]

>>> list(zip(*lst))
[(1, 3, 2, 6), (3, 4, 7, 5)]

因此,总体上:

>>> [max(v) for v in zip(*lst)]
[6, 7]

You can use zip which splits the pairs into two separate tuples:

>>> lst = [[1,3], [3,4], [2,7], [6,5]]

>>> list(zip(*lst))
[(1, 3, 2, 6), (3, 4, 7, 5)]

So, overall:

>>> [max(v) for v in zip(*lst)]
[6, 7]
烂柯人 2025-02-19 21:26:07

如果我们假设并非所有“行”都必须包含相同数量的列,尽管给定的示例,我们可以获得与:min(Map(Len,lst)) bund的最小“列” 。

我们可以使用它来迭代列:col_num in range(min(map(len,lst))))。

我们可以在lst 中使用续写行,因此将其放在一起:

[[row[col_num] for row in lst] for col_num in range(min(map(len, lst)))]
# => [[1, 3, 2, 6], [3, 4, 7, 5]]

但是我们只需要最大值,max就可以喂食一个生成器表达式而不是列表为了使其保持更高的记忆效率,因此:

[max(row[col_num] for row in lst) for col_num in range(min(map(len, lst)))]
# => [6, 7]

If we assume not all "rows" will necessarily contain the same number of columns, despite the given example, we can get the minimum "column" bound with: min(map(len, lst)).

We can use this to iterate over the columns: for col_num in range(min(map(len, lst))).

And we can iterate over rows with for row in lst, so putting this together:

[[row[col_num] for row in lst] for col_num in range(min(map(len, lst)))]
# => [[1, 3, 2, 6], [3, 4, 7, 5]]

But we just need the maximum, and max can be fed a generator expression instead of a list to keep this a bit more memory-efficient, so:

[max(row[col_num] for row in lst) for col_num in range(min(map(len, lst)))]
# => [6, 7]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文