碎碎念
写完之后发现我好多function根本不会,但反正看着其他人的範例也是加减学
题干
会有一个list里面可能有很多list,要把它们变成只有一层,也就是扁平化
解题思路
一样找我们的AI大神
我要写一个确认list是否还有子list的pyhton程式我要检查子list有没有list的递迴历遍list元素,如果是有子list,将元素取出,存入母list
然后基本上就可以得到差不多的东西
稍微修改一下配合题目要使用的def(对,外层的三个def是题目要求的,超麻烦)
class NestedIterator: def __init__(self, nestedList): self.nestedList = nestedList self.flat_list = [] self.index = 0 def flatten(currentList): """ 此函数接受一个列表,并递归地将其扁平化。 """ for item in currentList: if item.isInteger(): # 直接检查整数(题目是说整数) self.flat_list.append(item.getInteger()) else: # 检查子列表 flatten(item.getList()) flatten(self.nestedList) def next(self) : """ 返回扁平列表中的下一个元素。 """ if self.hasNext(): result = self.flat_list[self.index] self.index += 1 return result def hasNext(self) -> bool: """ 检查是否还有更多的元素。 """ return self.index < len(self.flat_list)