Python list + list vs. list.append()

电脑杂谈  发布时间:2020-02-02 16:01:46  来源:网络整理

周顺利任然爱情1加1_list[1].append python_解放牌ca5169xxypk2l2ra80-1

可以将文章内容翻译成英文,广告屏蔽软件可能会导致该功能失灵(如失效,请关掉广告屏蔽软件后再试):

Today I spent about 20 minutes trying to figure out why this worked as expected:

users_stories_dict[a] = s + [b]  

周顺利任然爱情1加1_解放牌ca5169xxypk2l2ra80-1_list[1].append python

but this would have a None value:

users_stories_dict[a] = s.append(b) 

Anyone know why the append function does not return the new list? I'm looking for some sort of sensible reason this decision was made; it looks like a Python novice gotcha to me right now.

周顺利任然爱情1加1_解放牌ca5169xxypk2l2ra80-1_list[1].append python

append works by actually modifying a list, and so all the magic is in side-effects. Accordingly, the result returned by append is None. In other words, what one wants is:

s.append(b)

and then:

周顺利任然爱情1加1_list[1].append python_解放牌ca5169xxypk2l2ra80-1

users_stories_dict[a] = s

But, you've already figured that much out. As to why it was done this way, while I don't really know, my guess is that it might have something to do with a 0 (or false) exit value indicating that an operation proceeded normally, and by returning None for functions whose role is to modify their arguments in-place you report that the modification succeeded.

But I agree that it would be nice if it returned the modified list back. At least, Python's behavior is consistent across all such functions.

周顺利任然爱情1加1_解放牌ca5169xxypk2l2ra80-1_list[1].append python

The append() method returns a None, because it modifies the list it self by adding the object appended as an element, while the + operator concatenates the two lists and return the resulting list

eg:

a = [1,2,3,4,5] b = [6,7,8,9,0]  print a+b         # returns a list made by concatenating the lists a and b >>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]  print a.append(b) # Adds the list b as element at the end of the list a and returns None >>> None  print a           # the list a was modified during the last append call and has the list b as last element >>> [1, 2, 3, 4, 5, [6, 7, 8, 9, 0]] 

So as you can see the easiest way is just to add the two lists together as even if you append the list b to a using append() you will not get the result you want without additional work


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-139367-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      • 何宁
        何宁

        台湾如果敢宣布独立

      • 连旭东
        连旭东

        不然不会说出解决男女失衡解决办法是公用妻子

      热点图片
      拼命载入中...