Skip to main content
 首页 » 编程设计

python之获取 ['76 125 94 95 122 96 126 123 124 87' 中的最高数字]

2025年05月04日1052php

给定一个单元素列表,例如:

['76 125 94 95 122 96 126 123 124 87'] 

我想从字符串中找出最大的数字(作为 int)。而不是提取列表的第零个元素,然后拆分成一个新列表,然后将这个新列表的每个元素转换为整数,然后最后得到 max(),是否有一个(或二)可以做同样事情的类轮?

请您参考如下方法:

Rather than extract the zeroth element of the list, then split into a new list, then convert each element of this new list to ints, and then finally get the max(), is there a one (or two) liner that can do the same things?

你可以像这样在一行中完成所有这些

>>> max(map(int, data[0].split())) 
126 

我们可以简单地使用生成器表达式,而不是使用 map(在 Python 2 中返回一个 list),它将按需生成值。

>>> max(int(item) for item in data[0].split()) 
126