[英]How to append elements from 2 short lists into another big list of tuples?
Say I have the following lists: 说我有以下列表:
l1 = [('a','b','c'),('d','e','f'),('g','h','i'),('j','k','l')]
l2 = ['x','y','z']
l3 = ['m','n']
I want to extract elements from l2 and l3, then append l2[i]( i in range(len(l2))
) as the first element inside every tuple, and l3[i]( i in range(len(l2))
) as the last element inside every tuple. 我想从l2和l3中提取元素,然后将l2 [i](
i in range(len(l2))
)中作为每个元组内的第一个元素追加,并且l3 [i]( i in range(len(l2))
)作为每个元组中的最后一个元素。
so the result will look like the followings: 所以结果如下:
l1 = [('x','a','b','c','m'),('x','a','b','c','n'),('y','a','b','c','m'),('y','a','b','c','n'), ('z','a','b','c','m'),('z','a','b','c','n')]
and yes, the len of l1 will be increased. 是的,l1的len将会增加。
You can do that with the help of itertools.chain.from_iterable
and itertools.product
, and get the cartesian product, like this 你可以在
itertools.chain.from_iterable
和itertools.product
的帮助下做到这一点,并得到笛卡尔积,就像这样
>>> from itertools import chain, product
>>> from pprint import pprint
>>> pprint([tuple(chain.from_iterable(i)) for i in product(l2, [l1[0]], l3)])
[('x', 'a', 'b', 'c', 'm'),
('x', 'a', 'b', 'c', 'n'),
('y', 'a', 'b', 'c', 'm'),
('y', 'a', 'b', 'c', 'n'),
('z', 'a', 'b', 'c', 'm'),
('z', 'a', 'b', 'c', 'n')]
You are finding the cartesian product between l2
, the first element of l1
and l3
. 您正在
l2
之间找到笛卡尔积, l1
是l1
和l3
的第一个元素。 Since the result will be a tuple with the element from l2
(a string) and the first element of l1
(a tuple) and an element from l3
(a string), we flatten it with chain.from_iterable
. 因为结果将是一个元组来自
l2
(一个字符串)和l1
的第一个元素(一个元组)和一个来自l3
的元素(一个字符串),我们用chain.from_iterable
它展平。
Let's say we don't flatten the tuples, then this is what you will get 假设我们不会使元组变平,那么这就是你将得到的
>>> pprint([tuple(items) for items in product(l2, [l1[0]], l3)])
[('x', ('a', 'b', 'c'), 'm'),
('x', ('a', 'b', 'c'), 'n'),
('y', ('a', 'b', 'c'), 'm'),
('y', ('a', 'b', 'c'), 'n'),
('z', ('a', 'b', 'c'), 'm'),
('z', ('a', 'b', 'c'), 'n')]
This is why we use chain.from_iterable
and flatten the tuples. 这就是我们使用
chain.from_iterable
并展平元组的原因。
What about playing with zip
and list comprehension : 玩
zip
和列表理解怎么样:
>>> [zip(*i) for i in zip(zip(l2,l2),zip(l1,l1),(l3 for _ in range(2*len(l1))))]
[[('x', ('a', 'b', 'c'), 'm'), ('x', ('a', 'b', 'c'), 'n')], [('y', ('d', 'e', 'f'), 'm'), ('y', ('d', 'e', 'f'), 'n')], [('z', ('g', 'h', 'i'), 'm'), ('z', ('g', 'h', 'i'), 'n')]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.