名单*名单 [英] list*list
问题描述
必须有更好的方法将一个列表的元素乘以
另一个:
a = [1,2,3] >
b = [1,2,3]
c = []
for i in range(len(a)):
c.append(a [i] * b [i])
a = c
打印a
[1,4,9]
也许列表理解还是由NumPy更好地解决?
谢谢,
jab
There must be a better way to multiply the elements of one list by
another:
a = [1,2,3]
b = [1,2,3]
c = []
for i in range(len(a)):
c.append(a[i]*b[i])
a = c
print a
[1, 4, 9]
Perhaps a list comprehension or is this better addressed by NumPy?
Thanks,
jab
推荐答案
>必须有一种更好的方法将一个列表的元素乘以
> There must be a better way to multiply the elements of one list by
另一个:
a = [1,2,3]
b = [1, 2,3]
c = []
我在范围内(len(a)):
c.append(a [i] * b [i])
a = c
打印
[1,4,9]
或许是列表理解还是由NumPy更好地解决?
another:
a = [1,2,3]
b = [1,2,3]
c = []
for i in range(len(a)):
c.append(a[i]*b[i])
a = c
print a
[1, 4, 9]
Perhaps a list comprehension or is this better addressed by NumPy?
首先:如果您想要的是一个
枚举的索引,那么使用范围被认为是不好的风格,因为它实际上会创建一个大小的列表
指定。在这种情况下使用xrange。
你可以使用这样的listcomp:
c = [a [i] * b [i] for我在xrange(len(a))]
但也许更好的是拉链:
c = [av * bv for av,bv in zip(a,b)]
如果列表变大且可能是多维的,numpy当然是
的方式。
Diez
First of all: it''s considered bad style to use range if all you want is a
enumeration of indices, as it will actually create a list of the size you
specified. Use xrange in such cases.
You can use a listcomp like this:
c = [a[i] * b[i] for i in xrange(len(a))]
But maybe nicer is zip:
c = [av * bv for av, bv in zip(a, b)]
And if lists get large and perhaps multidemnsional, numpy certainly is the
way to go.
Diez
>必须有一种更好的方法将一个列表的元素乘以
> There must be a better way to multiply the elements of one list by
另一个:
a = [1,2,3]
b = [1, 2,3]
c = []
我在范围内(len(a)):
c.append(a [i] * b [i])
a = c
打印
[1,4,9]
或许列表理解还是由NumPy更好地解决?
another:
a = [1,2,3]
b = [1,2,3]
c = []
for i in range(len(a)):
c.append(a[i]*b[i])
a = c
print a
[1, 4, 9]
Perhaps a list comprehension or is this better addressed by NumPy?
>
a = [1,2,3]
b = [1,2,3]
c = [q * r表示q,r表示拉链(a) ,b)]
似乎对我有用。
-tim
a = [1,2,3]
b = [1,2,3]
c = [q*r for q,r in zip(a,b)]
seems to do the trick for me.
-tim
" Diez B. Roggisch" <德*** @ nospam.web.de>在消息中写道
新闻:4b ************* @ uni-berlin.de ...
"Diez B. Roggisch" <de***@nospam.web.de> wrote in message
news:4b*************@uni-berlin.de...
它被认为是坏的如果你想要的只是一个索引的枚举,因为它实际上会创建一个你指定的大小的列表。在这种情况下使用xrange。
it''s considered bad style to use range if all you want is a
enumeration of indices, as it will actually create a list of the size you
specified. Use xrange in such cases.
我很确定这种区别在2.5中消失了。
干杯,
Alan Isaac
I''m pretty sure this distinction goes away in 2.5.
Cheers,
Alan Isaac
这篇关于名单*名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!