这是扁平化嵌套序列的另一种方法。将序列展平后,可以很容易地进行检查以找到项目数。
def flatten(seq, container=None): if container is None: container = [] for s in seq: try: iter(s) # check if it's iterable except TypeError: container.append(s) else: flatten(s, container) return containerc = flatten([(1,2),(3,4),(5,[6,7,['a','b']]),['c','d',('e',['f','g','h'])]])print(c)print(c.count('g'))d = flatten([[[1,(1,),((1,(1,))), [1,[1,[1,[1]]]], 1, [1, [1, (1,)]]]]])print(d)print(d.count(1))
上面的代码打印:
[1, 2, 3, 4, 5, 6, 7, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']1[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]12
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)