包含字典的Python可迭代集合

时间:2017-01-14 21:11:42

标签: python dictionary collections iteration iterable

我正在尝试修改以下代码,以便MyCollection将包装字典。我仍然需要实现 iter next 方法,以便拥有“for element in collection”功能。我知道可以通过遍历值来轻松完成,但我需要这样做。有人能帮助我吗?

private string TreeViewToString(TreeView tv, string delimiter) {
    var result = new StringBuilder();

    foreach (TreeNode node in tv.Nodes) {
        TraverseNodes(node, delimited, result);
    }

    if (result.Length < delimiter.Length) {
        return result.ToString();
    } else {
        return result.ToString(0, result.Length - delimiter.Length); 
    }             
}

// recursive part
private void TraverseNodes(TreeNode node, string delimiter, StringBuilder result) {
    result.AppendFormat("{0}{1}", node.Text, delimiter);      // add node to string

    foreach (TreeNode subNode in node.Nodes) {
        TravserseNodes(subNode, delimiter, result);           // recurse into nodes children
    }
}

1 个答案:

答案 0 :(得分:0)

这从设计决定开始。当你迭代MyCollection你想要什么数据?如果它包含的字典的值你可以返回它的迭代器,然后你根本不实现__next__

class MyCollection:
    def __init__(self):
        self._data = {}

    def __iter__(self):
            '''
        Return an iterator of contained values
        '''
        return iter(self._data.values())