python初始化列表的一个小细节
今天用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)]
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?
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
Quality posts is the main to attract the visitors to
pay a visit the website, that’s what this website is providing.
I am regular visitor, how are you everybody? This piece of writing posted
at this website is actually pleasant.
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.
Wonderful article! We are linking to this great article
on our site. Keep up the great writing.
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
Your mode of explaining all in this post is genuinely fastidious, all be capable of without difficulty
know it, Thanks a lot.
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?
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!
This information is priceless. Where can I find out more?
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!