2

我有以下列表:

["stephane", "philippe", "hélène", ["hugo", "jean-michel", "fernand"], "gustave"]

我想这样订购:

["gustave", "hélène", ["fernand", "hugo", "jean-michel"], "philippe", "stephane"]

注意:如果用户后面有嵌套列表,则该列表必须位于该用户的右侧。

除此之外,所有嵌套列表的工作方式都相同。它是递归的。

4

2 回答 2

6

您的数据听起来会更好地表示为字典。连续元素具有特殊关系的列表听起来很奇怪。

如果您改为这样表示您的数据:

{
  "stephane": {}, 
  "philippe": {}, 
  "hélène": {
    "hugo": {}, 
    "jean-michel": {},
    "fernand": {},
  }, 
  "gustave": {},
}

然后您可以简单地对字典的键进行排序以获得您想要的顺序。

于 2011-09-12T13:23:38.560 回答
2

我使用了 Ned 的建议并提出了这个:

d = {
    "stephane": {}, 
    "philippe": {}, 
    "helene": {
        "hugo": {}, 
        "jean-michel": {},
        "fernand": {},
    }, 
    "gustave": {},
}

def sort_dict_as_list(d):
    sorted_list = []
    for k, v in sorted(d.items()):
        if k:    
            sorted_list.append(k)
        if v:
            sorted_list.append(v)
    return sorted_list

def sort_recursive(d):
    if d:
        for k, v in d.items():
            d[k] = sort_recursive(v)
        return sort_dict_as_list(d)
    else:
        return d

if __name__ == "__main__":
    print sort_recursive(d)

输出

python sortit.py
['gustave', 'helene', ['fernand', 'hugo', 'jean-michel'], 'philippe', 'stephane']

我还没有彻底测试它,但这是一个起点。我试图用列表作为数据结构来解决它,但我最终嵌套了递归函数,它太丑陋了...... Ned 的建议非常好。

于 2011-09-12T14:16:01.367 回答