可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
A flash question, I'm looking at the following code
from __future__ import division
import math
import time
def dft(x, inverse = False, verbose = False) :
t = time.clock()
N = len(x)
inv = -1 if not inverse else 1
X =[0] * N
for k in xrange(N) :
for n in xrange(N) :
X[k] += x[n] * math.e**(inv * 2j * math.pi * k * n / N)
if inverse :
X[k] /= N
t = time.clock() - t
if verbose :
print "Computed","an inverse" if inverse else "a","DFT of size",N,
print "in",t,"sec."
return X
and I'm wondering (I do not know python):
- what does the X =[0] * N line do?
- why the double asterisk ** ?
回答1:
The x = [0] * n
is demonstrated here:
>>> [0]*10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
It 'multiplies' the list elements
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The **
is the power operator
>>> 3**2
9
Although be careful, it can also be **kwargs (in a different context), see more about that here Proper way to use **kwargs in Python
回答2:
The [0] * x
creates a list with x
elements. So,
>>> [ 0 ] * 5
[0, 0, 0, 0, 0]
>>>
Be warned that they all point to the same object. This is cool for immutables like integers but a pain for things like lists.
>>> t = [[]] * 5
>>> t
[[], [], [], [], []]
>>> t[0].append(5)
>>> t
[[5], [5], [5], [5], [5]]
>>>
The **
operator is used for exponentation.
>>> 5 ** 2
25
回答3:
X = [0] * N
creates an array of zeros of N
length. For example:
>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
**
is the power operator.
>>> 2 ** 2
4
回答4:
what does the X =[0] * N line do?
[0]
is a sequence containing a single element – 0
. Multiplying a sequence times n
means concatenating it n
times to itself. That is, the result is a sequence containing n
zeros.
why the double asterisk ** ?
It’s the power operator: b ** e
= be.
回答5:
X =[0] * N
, produces a list of size N, with all N elements being the value zero. for example, X = [0] * 8
, produces a list of size 8.
X = [0, 0, 0, 0, 0, 0, 0, 0]
Pictorial representation will be like,
Technically, all eight cells of the list reference the same object. This is because of the fact that lists are referential structures in python.
and, if you try to assign a new value to list, say X[2] = 10
, this does not technically change the value of the existing integer instance. This computes a new integer, with value 10, and sets cell 2 to reference the newly computed value.
Pictorial representation,
**
is power operator and computes the power of a number. for example, 5 ** 2
results in 25.
回答6:
1) It initialises a list containing N 0's.
2) **
is the exponentiation operator
回答7:
[0] * N
creates a list of size N which contains only 0's
the **
is a notation for raising the left side to the power of right side
Disclaimer:
[a] * N
where a
is a reference to an object will copy the reference, it won't make copies of a
inside the list generated