列表A
具有任意嵌套程度,列表B
的嵌套结构等同于A(或更深),我们怎样才能为所有相应元素创建元组列表?例如:
A = ['a', ['b', ['c', 'd']], 'e']
B = [1, [2, [3, [4, 5]]], 6]
>>>
[('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]
答案 0 :(得分:3)
基本上,您需要做的就是同时迭代a
和b
并返回a
和b
的值,如果{{1}的当前元素不是列表。由于您的结构是嵌套的,我们无法对它们进行线性迭代。这就是我们使用递归的原因。
此解决方案假定a
中B
中的每个元素都始终存在相应的元素。
A
答案 1 :(得分:2)
你想要一个递归的zip函数:
from itertools import izip
def recurse_zip(a, b):
zipped = izip(a, b)
for t in zipped:
if isinstance(t[0], list):
for item in recurse_zip(*t):
yield item
else:
yield t
演示:
>>> A = ['a', ['b', ['c', 'd']], 'e']
>>> B = [1, [2, [3, [4, 5]]], 6]
>>> print(list(recurse_zip(A, B)))
[('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]
注意:
izip
有助于让它变得懒惰 - python3.x的zip
也可以正常工作。yield from
)中使用yield from recurse_zip(*t)
语法。答案 2 :(得分:1)
您可以使用zip进行迭代以创建列表
A = ['a', ['b', ['c', 'd']], 'e']
B = [1, [2, [3, [4, 5]]], 6]
def make_tuples(list1, list2):
tups = []
def _helper(l1, l2):
for a, b in zip(l1, l2):
if isinstance(a, list) and isinstance(b, list):
_helper(a, b)
else:
tups.append((a, b))
_helper(list1, list2)
return tups
make_tuples(A, B)
或简单的元组生成器 -
def tuples_generator(l1, l2):
for a, b in zip(l1, l2):
if isinstance(a, list) and isinstance(b, list):
tuples_generator(a, b)
else:
yield (a, b)
In : make_tuples(A, B)
Out: [('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]
答案 3 :(得分:0)
你可以使用zip,这是我的答案。
a = ['a', ['b', ['c', 'd']], 'e']
b = [1, [2, [3, [4, 5]]], 6]
c = []
def CheckIfList(a):
for k in a:
print 'k is:', k
if isinstance(k, (list, tuple)):
return True
return False
def ZipAllElements(a, b, c):
if CheckIfList(a):
r = zip(a, b)
for i in r:
if isinstance(i[0], (list, tuple)):
ZipAllElements(i[0], i[1], c)
else:
c.append(i)
else:
c.extend(list(zip(a, b)))
ZipAllElements(a, b, c)
print c
答案 4 :(得分:0)
In [3]: from compiler.ast import flatten
In [4]: zip(flatten(A), flatten(B))
Out[4]: [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]