[英]Selecting the maximum value from different list in python
I have a list that looks like this, which I was able to get after scraping a website, but in this case these are different dimension of images from the website:我有一个看起来像这样的列表,我可以在抓取网站后获得,但在这种情况下,这些是来自网站的不同维度的图像:
[72, 72]
[95, 96]
[13, 60]
[227, 973]
I have tried this but it is not giving me what I want:我已经尝试过了,但它并没有给我想要的东西:
for items in height, width:
dimension.append(items)
print(max(dimension))
I want to be able to select the one with the maximum value which is:我希望能够 select 最大值为:
[227, 973]
I assume you have a two-dimensional list and are interested in finding the sublist, which contains the maximal element.我假设您有一个二维列表,并且有兴趣找到包含最大元素的子列表。
To find this, you can simply use pythons build in max
function and provide a comparison function via the key
parameter.要找到这一点,您可以简单地使用 pythons build in max
function 并通过key
参数提供比较 function。 The key parameter takes a function of which the result is used for comparison, so for example: key=lambda sublist: max(sublist)
. key 参数取一个 function ,其结果用于比较,例如: key=lambda sublist: max(sublist)
。 In this case, you can even simply pass the max()
function itself as key
在这种情况下,您甚至可以简单地将max()
function 本身作为key
传递
To sum it up, something like this should work for you:总而言之,这样的事情应该适合你:
x = [[72, 72], [95, 96], [13, 60], [227, 973]]
max_pair = max(x, key=max)
print(max_pair)
After the discussion with you , I assume you get the dimension values in a for loop (and don't have them in a list at the beginning) and want to get the max at the end.在与您讨论之后,我假设您在 for 循环中获得维度值(并且在开始时没有将它们放在列表中)并且希望在最后获得最大值。 I modified your code a bit and hope this works for you.我稍微修改了您的代码,希望这对您有用。 It still uses the same idea as mentioned before:它仍然使用与前面提到的相同的想法:
dimensions = []
for something in something_else:
image = get_image()
height, width, _ = image.shape
dimensions.append([height, width])
max_dimension = max(dimensions, key=max)
print(max_dimension)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.