交错元组
Interleaving tuple
定义一个函数 interleaved_tuple_two
接受两个参数,tuple_a
和 tuple_b
return 是一个交错值的元组,它交错 tuple_b
的一个值对于 tuple_a
的每两个值。假设 tuple_a
总是 tuple_b
的两倍。
例如:
tuple_a = (1,3,5,7,9,11,13,15)
tuple_b = (2,4,6,8)
interleaved_tuple_two(tuple_a, tuple_b)
将 return:
(1, 3, 2, 5, 7, 4, 9, 11, 6, 13, 15, 8)
目前,我有这个,但它不正确。不太确定如何对此进行改进
def interleaved_tuple_two(tuple_a, tuple_b):
return [val for pair in zip(tuple_a, tuple_b) for val in pair]
您可以对三个列表使用 zip,前两个 tuple_a
一次跳过一个值但起始位置不同,然后第三个是 tuple_b
.
tuple_a = (1, 3, 5, 7, 9, 11, 13, 15)
tuple_b = (2, 4, 6, 8)
tuple_c = tuple(
v
for triple in zip(tuple_a[::2], tuple_a[1::2], tuple_b)
for v in triple
)
print(tuple_c)
另一种选择是使用索引并将其映射到适当的查找:
tuple_c = tuple(
v
for i in range(len(tuple_b))
for v in (tuple_a[i*2], tuple_a[i*2+1], tuple_b[i])
)
您也可以使用 itertools.chain
来避免理解:
from itertools import chain
tuple_a = (1, 3, 5, 7, 9, 11, 13, 15)
tuple_b = (2, 4, 6, 8)
tuple_c = tuple(chain(*zip(tuple_a[::2], tuple_a[1::2], tuple_b)))
print(tuple_c)
定义一个函数 interleaved_tuple_two
接受两个参数,tuple_a
和 tuple_b
return 是一个交错值的元组,它交错 tuple_b
的一个值对于 tuple_a
的每两个值。假设 tuple_a
总是 tuple_b
的两倍。
例如:
tuple_a = (1,3,5,7,9,11,13,15)
tuple_b = (2,4,6,8)
interleaved_tuple_two(tuple_a, tuple_b)
将 return:
(1, 3, 2, 5, 7, 4, 9, 11, 6, 13, 15, 8)
目前,我有这个,但它不正确。不太确定如何对此进行改进
def interleaved_tuple_two(tuple_a, tuple_b):
return [val for pair in zip(tuple_a, tuple_b) for val in pair]
您可以对三个列表使用 zip,前两个 tuple_a
一次跳过一个值但起始位置不同,然后第三个是 tuple_b
.
tuple_a = (1, 3, 5, 7, 9, 11, 13, 15)
tuple_b = (2, 4, 6, 8)
tuple_c = tuple(
v
for triple in zip(tuple_a[::2], tuple_a[1::2], tuple_b)
for v in triple
)
print(tuple_c)
另一种选择是使用索引并将其映射到适当的查找:
tuple_c = tuple(
v
for i in range(len(tuple_b))
for v in (tuple_a[i*2], tuple_a[i*2+1], tuple_b[i])
)
您也可以使用 itertools.chain
来避免理解:
from itertools import chain
tuple_a = (1, 3, 5, 7, 9, 11, 13, 15)
tuple_b = (2, 4, 6, 8)
tuple_c = tuple(chain(*zip(tuple_a[::2], tuple_a[1::2], tuple_b)))
print(tuple_c)