今天用python写算法的时候注意到python初始化list的一个小细节

当我们想得到一个长度为n的列表时,一般可以

l = [0 for i in range(n)
# or
l = [0]*n

对于第二种方式要注意的是,如果数组元素是引用类型(比如对象,string等),那么这个list中每个元素保存的都是相同的引用

a = object()
l = [a]*2
id(l[0])==id(l[1]) # turn out True

所以如果想得到一个m行n列的二维数组,一定要小心,不能如下初始化

n = 3
m = 3
l = [[0]*n]*m
l[0][1] = 1
l[1][1]==1 # trun out True!!

所以还是老老实实的初始化吧

l = [[0 for _ in range(n)] for _ in range(m)]

12 对 “python初始化列表的一个小细节”的想法;

  1. Thank you, I’ve recently been looking for information approximately this topic for a while and yours is the greatest I have found out till now.
    But, what in regards to the conclusion? Are you certain concerning the
    source?

  2. Unquestionably believe that that you said. Your favourite reason seemed to be on the web the simplest factor to consider of.
    I say to you, I definitely get annoyed even as folks consider issues
    that they plainly do not recognise about. You controlled to hit the nail upon the
    highest as neatly as defined out the entire thing with no need side-effects , folks
    can take a signal. Will likely be again to get more. Thank you

  3. Appreciating the dedication you put into your website and in depth information you offer.
    It’s awesome to come across a blog every once in a while that isn’t the
    same outdated rehashed information. Fantastic read!

    I’ve bookmarked your site and I’m including your RSS feeds to
    my Google account.

  4. Undeniably believe that which you said. Your favorite reason seemed to be
    on the internet the easiest thing to be aware of.
    I say to you, I certainly get irked while people think about worries
    that they just don’t know about. You managed
    to hit the nail upon the top and defined out the whole thing
    without having side-effects , people could take a signal.
    Will likely be back to get more. Thanks

  5. fantastic issues altogether, you just won a emblem new reader.
    What could you recommend in regards to your put up that you simply made some days in the past?

    Any positive?

  6. You actually make it seem so easy with your presentation but
    I find this matter to be actually something which
    I think I would never understand. It seems too complex
    and extremely broad for me. I am looking forward for
    your next post, I will try to get the hang of it!

  7. Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your website?
    My website is in the very same area of interest as yours
    and my users would genuinely benefit from some of the information you present here.
    Please let me know if this alright with you.
    Regards!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注