如何在Python中找到一个对象列表中字符串的最大长度

3
class XYZ:

    def __init__(self, name, score):
        self.name = name
        self.score = score


l = []     # l is the list of objects

l.append(XYZ('Anmol', 10))
l.append(XYZ('Andrew', 200))
l.append(XYZ('Johnson', 3000))

在上面的代码中,l是包含三个对象的列表,每个对象都有一个名称(字符串)和一个分数(整数),那么我怎样才能找到该对象列表中名称的最大长度呢?

在我们的程序中,名称最长的是Johnson,它的长度为7。因此程序应该输出7。如何做到呢?


4
max(len(xyz.name) for xyz in l) - Patrick Haugh
4个回答

6

使用列表推导式,而不使用lambda,代码如下:

 result = max(len(x) for x in l)

基本上,这做了以下几件事情(从右到左分解列表理解有助于理解):
  1. in l: iterates over l
  2. for x: assigns each element of l to the variable x during the iteration
  3. len(x): get the length of each variable x within the list l
  4. list comprehensions put the output into a list format naturally, so at this point we have a list of all the lengths of strings, like:

    [5, 6, 7]
    
  5. max(...): simply gets the largest number from the list of lengths

希望这个解释有助于理解正在发生的事情。

3
longest_xyz = max(l, key=lambda item: len(item.name))
print("The length of the longest string is ", len(longest_xyz.name))

3
这是一种功能性的方法:
from operator import attrgetter

result = max(map(len, map(attrgetter('name'), l)))

# 7

3

这不总是适用的,但如果根据name的长度比较是您类的逻辑的一部分,您可以实现特殊的类方法__lt____eq__

class XYZ:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __lt__(self, other):
        return len(self.name) < len(other.name)

    def __eq__(self, other):
        return self.name == other.name and self.score == other.score

结果如下:
l = [XYZ('Anmol', 10), XYZ('Andrew', 200), XYZ('Johnson', 3000)]

max(l).name # 'Johnson'

请注意,这样做还将为您的类实例指定比较运算符( == <>)以及 sorted 的行为。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接