python - 嵌套列表 - Python
问题描述
我需要编写执行以下操作的 Python 方法的主体:
1) 获取一个列表,其中 list[0] 是一个字符串,而 list[1] 是一个看起来相同的列表或 None
2)打印列表的每个字符串
我必须使用 while 循环,而不是使用列表理解或展平。
def pick_cherries_iter(field):
""""e.g.
>>> cherry_field = ['cherry1', ['cherry2', ['cherry3', ['cherry4', ['Yay!!!', None]]]]]
>>> pick_cherries_iter(cherry_field)
cherry1
cherry2
cherry3
cherry4
Yay!!!"""
_______________________
_______________________
_______________________
_______________________
while _________________:
_______________________
_______________________
_______________________
我知道对于上面的示例,如果我为cherry_field[1][0] 打印cherry_field[0] 或cherry1 或cherry_filed[1][1][0] 等打印cherry1,我可以打印cheery1,但是我不知道如何使用 while 循环遍历这些元素。
解决方案
我会递归地执行此操作,因为您无法知道元素是否为列表。
#!/usr/bin/python -E
cherry_field = ['cherry1', ['cherry2', ['cherry3', ['cherry4', ['Yay!!!', None]]]]]
def print_list(field):
i = 0
list_length = len(field)
while i < list_length:
if field[i] is not None and type(field[i]) is not list:
print(field[i])
else:
if field[i] is not None:
print_list(field[i])
i += 1
if i < list_length and type(field[i]) is list:
print_list(field[i])
i += 1
def pick_cherries(field):
if type(field) is list:
print_list(field)
pick_cherries(cherry_field)
推荐阅读
- javascript - 限制 airDatepickerInput() 不允许单个日期选择
- python-3.x - 选择文件中的每个字母,然后找到其 ASCII 值(Python)
- java - 没有填充的 Java RSA
- python - 改变数组的值
- javascript - 页面加载时如何从使用jquery动态生成的复选框组中检索值
- spring-boot - 使用 Swagger 记录自定义 API 响应
- javascript - 将元素添加到 Uint8ClampedArray 类型数组的快速方法
- r - rshiny 渲染时间滑块或选择器
- html - 响应式 SVG - 视口内在尺寸
- powershell - 如何使用powershell获取具有特定数据存储已用空间25%以上的vmware vm列表?