相关疑难解决方法(0)

在Python中没有[]的列表理解

加入清单:

>>> ''.join([ str(_) for _ in xrange(10) ])
'0123456789'
Run Code Online (Sandbox Code Playgroud)

join 必须采取迭代.

显然,join这个论点是[ str(_) for _ in xrange(10) ],这是一个列表理解.

看这个:

>>>''.join( str(_) for _ in xrange(10) )
'0123456789'
Run Code Online (Sandbox Code Playgroud)

现在,join这个论点只是str(_) for _ in xrange(10),不[],但结果是一样的.

为什么?是否str(_) for _ in xrange(10)也会产生一个列表或一个可迭代?

python list-comprehension

76
推荐指数
4
解决办法
1万
查看次数

self [identifier] = some_value在这段代码中做了什么?

我只是想在Python中学习K-ary树实现并且遇到了这个链接:http: //www.quesucede.com/page/show/id/python-3-tree-implementation

在tree.py文件中,有一段代码如下:

class Tree:

    def __init__(self):
        self.__nodes = {}

    @property
    def nodes(self):
        return self.__nodes

    def add_node(self, identifier, parent=None):
        node = Node(identifier)
        self[identifier] = node

        if parent is not None:
            self[parent].add_child(identifier)

        return node

    # ... ...

    def __getitem__(self, key):
        return self.__nodes[key]

    def __setitem__(self, key, item):
        self.__nodes[key] = item
Run Code Online (Sandbox Code Playgroud)

什么是self[identifier]?这是一个清单吗?这真令人困惑.有人可以解释和/或指出一些使用self作为列表的文档吗?

python

6
推荐指数
1
解决办法
136
查看次数

标签 统计

python ×2

list-comprehension ×1