python - 返回嵌套列表中元素的函数
问题描述
所以这是我得到的练习:
def unflatten(ls):
"""returns elements in nested lists where the last element is None
ls = list with string elements
Examples:
>>> unflatten(['Hello', 'world'])
['Hello', ['world', None]]
>>> unflatten(['Hello'])
['Hello', None]
>>> unflatten(['No', 'more', 'cherries', 'please!'])
['No', ['more', ['cherries', ['please!', None]]]]
"""
"""write your code here"""
所以我写了这个:
newls = []
x = 0
for x in range(len(ls)):
if x==0:
newls.append(ls[x])
elif x == len(ls)-1:
newls.append([ls[x], None])
else:
newls.append([ls[x], ])
print(newls)
这仅对 2 个元素的列表是正确的 有人可以提出任何答案吗?
解决方案
也许我忽略了一些事情,但这种简单的递归方法还不够:
def unflatten(ls):
if ls:
return [ls[0], unflatten(ls[1:])]
>>> unflatten(['Hello', 'world'])
['Hello', ['world', None]]
>>> unflatten(['Hello'])
['Hello', None]
>>> unflatten(['No', 'more', 'cherries', 'please!'])
['No', ['more', ['cherries', ['please!', None]]]]
有很多方法可以以或多或少的可读/显式方式打扮这匹马,对于单行你可以包含一个条件表达式:
def unflatten(ls):
if ls:
head, *tail = ls
return [head, unflatten(tail)]
return None # not necessary
def unflatten(ls):
return [ls[0], unflatten(ls[1:])] if ls else None
推荐阅读
- python - 我很难理解伪代码
- d3.js - 从强制边缘捆绑创建路径不与 D3 中的节点位置对齐
- python - 用python自动打开微软商店应用程序/游戏?
- javascript - 在精美图库中的图像上显示文本时出现问题
- r - R 工作室 youtubecaption
- mysql - MySql 数据库连接问题
- python-3.x - 无法使用 pandas 将对象 dtype 转换为 mm:ss:ms 格式的持续时间
- javascript - IE 将 window.closed 显示为 true,即使窗口处于打开状态
- c# - 使用剃须刀页面时处理 ASP .NET 3.1 核心控制器中的异常
- python - 如何制作多行 Pandas 数据框标头,使其不会太长