python - 如何在python函数中传递具有属性值的对象
问题描述
我正在进行排序,但我无法以特定方式调用该函数。
基本上,我想要做的是创建一个函数,该函数接受具有属性值的对象节点列表,并返回一个列表,其中原始列表中的项目存储到子列表中。相同值的项目应该在同一个子列表中,并按降序排序。
为了继续代码,我想知道这个参数应该是什么。
def advanced_sort(<What will come here according to the call>):
函数调用:
advanced_sort([Node(1), Node(2), Node(1),Node(2)])
任何人都可以帮我解决代码吗?提前致谢。
解决方案
advanced_sort
接受一个参数:一个列表(或者可能是一个任意的迭代)。因此,签名只有一个参数:
def advanced_sort(nodes):
忽略类型提示,签名不会也不能反映单个参数的内部结构;它只是一个名称,用于引用函数体内传递的值。
在正文中,您可以编写代码,假设它nodes
是一个列表,并且列表的每个元素都是一个Node
实例,因此您可以执行诸如假设每个值作为Value
属性的事情。
def advanced_sort(nodes):
# If nodes is iterable, then x refers to a different
# element of the iterable each time through the loop.
for x in nodes:
# If nodes is a list of Node instances, then
# x is a Node instance, and thus you can access
# its Value attribute in the normal fashion.
print("Found value {}".format(x.Value))
假设Node
like的定义
class Node:
def __init__(self, v):
self.Value = v
的上述定义advanced_sort
将产生以下输出:
>>> advanced_sort([Node(3), Node(2), Node(1),Node(2)])
Found value 1
Found value 2
Found value 3
Found value 4
推荐阅读
- android - 使用多窗口在部分屏幕中打开不同的应用程序
- java - 配置两个数据库时无法从 mongo 集合中获取数据 - mongotemplate
- go - 是否可以在 Go 中定义匿名接口实现?
- tfs - 从 TFS 迁移到 AzureDevOps
- java - getFilter() 可以搜索过滤后的数据,不能显示原始数据
- bundler - 使用汇总生成的文件覆盖命名空间
- html - IE中的Flex项目宽度未调整大小
- serialization - Use of SerializationFeature.WRAP_ROOT_VALUE ahead of xmlRootElement
- python - 使用python数据表按组排列前N行
- html - CSS中输入的几个ID