假设我有一个列表如下:
myList = [[1.,1.,6.],[2.,4.,4.],[3.,3.,3.]]
现在我想对myList
中的每个列表应用某个函数,为了简单起见,它看起来像这样(它只是将列表的每个元素除以此列表的总和)。
def changeVal(l):
return map(lambda x: x/sum(l),l)
将其应用于myList
会给我:
modList = map(lambda x: changeVal(x), myList)
[[0.125, 0.125, 0.75],
[0.2, 0.4, 0.4],
[0.3333333333333333, 0.3333333333333333, 0.3333333333333333]]
但我真正想要的是将modList
的所有元素添加到myList
。我可以在for循环中执行此操作:
for sl in modList:
myList.append(sl)
给了我想要的输出:
[[1.0, 1.0, 6.0],
[2.0, 4.0, 4.0],
[3.0, 3.0, 3.0],
[0.125, 0.125, 0.75],
[0.2, 0.4, 0.4],
[0.3333333333333333, 0.3333333333333333, 0.3333333333333333]]
但是,我想在不使用for循环的情况下执行此操作,因为append
很慢。我试过了:
myList.append(*modList)
myList.extend(*modList)
这两个都给了我一个TypeError
:
TypeError: extend() takes exactly one argument (3 given)
以下是代码和所需的输出:
myList = [[1.,1.,6.],[2.,4.,4.],[3.,3.,3.]]
def changeVal(l):
return map(lambda x: x/sum(l),l)
modList = map(lambda x: changeVal(x), myList)
如何将modList
的元素添加到myList
以获得以下输出?
[[1.0, 1.0, 6.0],
[2.0, 4.0, 4.0],
[3.0, 3.0, 3.0],
[0.125, 0.125, 0.75],
[0.2, 0.4, 0.4],
[0.3333333333333333, 0.3333333333333333, 0.3333333333333333]]
答案 0 :(得分:1)
这里使用的正确函数是extend()
,但是extend接受你想要扩展的列表,而不是该列表的元素。尝试像 -
myList.extend(modList)
示例 -
>>> l = [[1,2],[3,4]]
>>> l1 = [[5,6],[7,8]]
>>> l.extend(l1)
>>>
>>> l
[[1, 2], [3, 4], [5, 6], [7, 8]]
虽然如果在其他任何地方都没有使用modList
,你可以完全避免创建中间列表,通过做 -
myList.extend(map(lambda x: changeVal(x), myList))
两种方法的时间结果 -
In [42]: def func1():
....: l = [[1,2],[3,4]]
....: l1 = [[5,6],[7,8]]
....: for i in l1:
....: l.append(i)
....: return l
....:
In [43]: def func2():
....: l = [[1,2],[3,4]]
....: l1 = [[5,6],[7,8]]
....: l.extend(l1)
....: return l
....:
In [44]:
In [44]: %timeit func1()
The slowest run took 8.35 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1 µs per loop
In [45]: %timeit func2()
The slowest run took 9.11 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 794 ns per loop
In [47]: %timeit func1()
The slowest run took 7.74 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 983 ns per loop
In [46]: %timeit func2()
1000000 loops, best of 3: 799 ns per loop
所以使用.extend()
比for
循环和.append()
快一点。