Python 列表操作

标签 python list coding-style

这是我的代码,但它看起来像非 python。

def __contains__(self, childName):
    """Determines if item is a child of this item"""
    for c in self.children:
        if c.name == childName:
            return True
    return False

最“ python ”的做法是什么?使用 lambda 过滤器功能?出于某种原因,很少有在线示例实际使用您比较属性的对象列表,它们总是显示如何使用实际字符串列表来执行此操作,但这不是很现实。

最佳答案

我会使用:

return any(childName == c.name for c in self.children)

这很短,并且与您的代码具有相同的优点,即它会在找到第一个匹配项时停止。

如果你经常这样做,并且速度是一个问题,你可以创建一个新的属性,它是一组子名称,然后只需使用 return childName in self.childNames,但随后您必须更新更改子项的方法以保持 childNames 最新。

关于Python 列表操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7115525/

相关文章:

python - 迭代具有不同元素的列表

python - 在 Python 中从选定的列表元素中查找最大的数字

java - 如何将 List<A> 转换为 List<B>?

objective-c - cocoa 风格 : using polymorphism in collections

python - 正则表达式 : Finding alpha numeirc sub-strings but not strictly alphabetic and might be fully numeric

python - 如何用openCV对准绿带和红外图像?

python - 比 Python 的 find 更强大的方法?正则表达式问题?

python - 在networkx图中,如何找到没有传出边的节点?

java - 我如何比较两个java文件的检查风格?

java - 直接返回评估结果或在返回之前应用三元运算符以增强可读性