[英]Create a list of tuples from two nested lists
擁有一個具有任意嵌套程度的列表A
,以及一個具有與A相同( 或更深 )的嵌套結構的列表B
,我們如何為所有對應元素創建一個元組列表? 例如:
A = ['a', ['b', ['c', 'd']], 'e']
B = [1, [2, [3, [4, 5]]], 6]
>>>
[('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]
基本上,所有你需要做的是,迭代a
和b
同時和返回的值a
和b
,如果當前元素a
不是列表。 由於您的結構是嵌套的,因此我們無法進行線性迭代。 這就是為什么我們使用遞歸。
這種解決方案假定有始終處於對應元素B
對中的每個元素A
。
def rec(a, b):
if isinstance(a, list):
# If `a` is a list
for index, item in enumerate(a):
# then recursively iterate it
for items in rec(item, b[index]):
yield items
else:
# If `a` is not a list, just yield the current `a` and `b`
yield a, b
print(list(rec(['a', ['b', ['c', 'd']], 'e'], [1, [2, [3, [4, 5]]], 6])))
# [('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]
您需要遞歸的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
於python3.3 +語法( yield from recurse_zip(*t)
您可以使用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)]
您可以使用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
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)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.