我编写了一个返回不同输出的函数,我需要为数组的每个元素迭代地调用该函数(作为迭代对象传递)。
但是,我只能以元组的形式检索输出,而且我不知道如何解压缩每个元素。 这是一个玩具示例:
def returninput(a,b,c):
return a,b,c
以下工作,但返回元组列表:
it=iter(np.linspace(1,100,100))
a=[returninput(elem, elem+1,elem+2) for elem in it]
In: a
Out: [(1.0, 2.0, 3.0),
(2.0, 3.0, 4.0),
(3.0, 4.0, 5.0),
(4.0, 5.0, 6.0),
.............
(99.0, 100.0, 101.0),
(100.0, 101.0, 102.0)]
我想为输出中的每个变量提供一个元素列表,所以我尝试了:
it=iter(np.linspace(1,100,100))
a,b,c=[returninput(elem, elem+1,elem+2) for elem in it]
但是我得到too many values to unpack (expected 3)
。
所需的输出为:
In: a
Out: [1.0, 2.0, 3.0, 4.0,...,100]
In: b
Out: [2.0, 3.0, 4.0, 5.0,...,101]
In: c
Out: [3.0, 4.0, 5.0, 6.0,...,102]
答案 0 :(得分:1)
使用zip
,则不需要中间函数:
a, b, c = list(zip(*[(elem, elem+1,elem+2) for elem in it]))
如果您希望a,b和c成为列表而不是元组:
a, b, c = [list(x) for x in zip(*[(elem, elem+1,elem+2) for elem in it])]
示例:
>>> a, b, c = list(zip(*[(elem, elem+1,elem+2) for elem in range(100)]))
>>> a
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99)
>>> b
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100)
>>> c
(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101)
在您的特定情况下,您将:
a,b,c=[list(x) for x in zip(*[returninput(elem, elem+1,elem+2) for elem in it])]