Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

math - What does the [0]*x syntax do in Python?

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 ** ?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...