我需要编写Python方法的主体,它执行以下操作:
1)接受一个列表,其中list是字符串,而list1要么是看起来相同的列表,要么没有
2)打印列表中的每一个字符串
我必须使用时间循环,而不是使用列表理解或扁平。
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或cherry1表示cherry_field1或cherry2 for cherry_filed1等,我可以打印cherry_field1,但是我不知道如何使用while循环来遍历这些元素。
发布于 2018-11-19 14:31:21
我觉得这应该对你有用。请检查一下。
使用While循环的:
def pick_cherry(field):
""""e.g.
>>> cherry_field = ['cherry1', ['cherry2', ['cherry3', ['cherry4', ['Yay!!!',None]]]]]
>>> pick_cherry(cherry_field)
cherry1
cherry2
cherry3
cherry4
Yay!!!"""
while field[1] != None:
temp = field[0]
print temp
field = field[1]
print field[0]
使用扁平(和递归)的:
flatten_field = []
def pick_cherry(field):
if field[1] != None:
flatten_field.append(field[0])
pick_cherry(field[1])
else:
flatten_field.append(field[0])
def flatten_func(field):
""""e.g.
>>> cherry_field = ['cherry1', ['cherry2', ['cherry3', ['cherry4', ['Yay!!!',None]]]]]
>>> flatten_func(cherry_field)
cherry1
cherry2
cherry3
cherry4
Yay!!!"""
pick_cherry(field)
for item in flatten_field:
print item
发布于 2018-11-19 14:18:03
我会递归地这样做,因为您无法知道某个元素是否是一个列表。
#!/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)
https://stackoverflow.com/questions/53376092
复制相似问题