.extend()方法返回“无",而不是我希望它返回的列表的所需组合 [英] .extend() method returning 'None' and not the desired combination of lists I intended it to return

查看:67
本文介绍了.extend()方法返回“无",而不是我希望它返回的列表的所需组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些基本的python方法. 现在,我正在尝试.extend()方法.我基本上有两个列表,并希望将它们合并为一个更大的列表以进行演示. 这在Shell环境中成功运行(成功完成了返回扩展列表的操作),但是在保存程序时却没有成功.当我要保存程序并运行它时,它将返回"None"的值.任何帮助将不胜感激.谢谢.

I am playing around with some basic python methods. Right now I am experimenting with the .extend() method. I basically have two lists and want to combine them into one larger list for demonstration purposes. This works successfully (successfully as in returning the extended list) in the Shell environment, but not when saving the program. When I want to save the program and run it, it returns the value of 'None'. Any assistance would be greatly appreciated. Thank you.

listOne=[1,2,3]

listTwo=[4,5,6]

listOneandlistTwo=listOne.extend(listTwo)

print(listOneandlistTwo)

推荐答案

listOneandlistTwo=listOne.extend(listTwo)

extend()扩展了给定的列表,但返回了None *,因此您已经扩展了listOne的内容,并包含了listTwo的内容,并将None分配给了listOneandListTwo.

extend() extends the given list but returns None*, so you have extended listOne with the contents of listTwo and assigned None to listOneandListTwo.

您想要的(假设您想保留listOnelistTwo原样)是这样的:

What you want (assuming you want to leave listOne and listTwo as they are) is this:

listOneandlistTwo = listOne + listTwo

*此行为是设计使然.如果extend()返回扩展列表,是否会返回扩展的副本?还是会返回扩展的原始列表?这是另一个要记住的细节,因此返回None意味着:哦,因为它返回None,所以它必须在适当的位置扩展列表,否则将毫无用处."

* This behavior is by design. If extend() returned the extended list, would it return a copy that's extended? Or would it return the original list extended? It's another detail to remember, so by returning None you are meant to think, "oh, since it's returning None it must be extending the list in place, otherwise it'd be useless."

这篇关于.extend()方法返回“无",而不是我希望它返回的列表的所需组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆