Python - 按字母顺序排列嵌套列表
我有以下列表:
["stephane", "philippe", "hélène", ["hugo", "jean-michel", "fernand"], "gustave"]
我想这样排序:
["gustave", "hélène", ["fernand", "hugo", "jean-michel"], "philippe", "stephane"]
注意:如果用户后面有一个嵌套列表,则该列表必须位于该用户的右侧。
除此之外,所有嵌套列表的工作方式都相同。这是递归的。
I have the following list:
["stephane", "philippe", "hélène", ["hugo", "jean-michel", "fernand"], "gustave"]
And I would like to order it like this:
["gustave", "hélène", ["fernand", "hugo", "jean-michel"], "philippe", "stephane"]
NB: If there is a nested list following a user, this list must stay to the right of this user.
In addition to that all nested lists works the same way. It's recursive.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的数据听起来最好用字典表示。连续元素具有特殊关系的列表听起来很奇怪。
如果您像这样表示数据:
那么您可以简单地对字典的键进行排序以获得您想要的顺序。
Your data sounds like it would be better represented as a dictionary. Lists where consecutive elements have a special relationship sound odd.
If you instead represented your data like this:
Then you can simply sort the keys of the dictionaries to get the order you want.
我使用了内德的建议并提出了这个:
输出
我还没有彻底测试它,但它是一个起点。我试图用列表作为数据结构来解决它,但最终我嵌套了递归函数,这太丑陋了......内德的提议非常好。
I've used Ned's proposal and came up with this:
Output
I haven't tested it thoroughly, but it's a starting point. I was trying to solve it with a list as a data structure, but I ended up nesting recursive functions and it was way too ugly... Ned's proposal was really good.