简体   繁体   English

尝试在Python中扩展列表时键入错误

[英]Type error when trying to extend a list in Python

I need to understand why : 我需要了解原因:

years = range(2010,2016)
years.append(0)

is possible, returning : 有可能,返回:

[2010,2011,2012,2013,2014,2015,0]

and

years = range(2010,2016).append(0)

or 要么

years = [0].extend(range(2010,2016))

doesn't work ? 不行吗?

I understand that it is a type error from the message I got. 我了解这是我收到的消息中的类型错误。 But I'd like to have a bit more explanations behind that. 但是,我想在此后面提供更多解释。

You are storing the result of the list.append() or list.extend() method; 您正在存储list.append()list.extend()方法的结果; both alter the list in place and return None . 改变位置列表,并返回None They do not return the list object again. 他们不会再次返回列表对象。

Do not store the None result; 不要存储“ None结果; store the range() result, then extend or append. 存储range()结果, 然后扩展或追加。 Alternatively, use concatenation: 或者,使用串联:

years = range(2010, 2016) + [0]
years = [0] + range(2010, 2016)

Note that I'm assuming you are using Python 2 (your first example would not work otherwise). 请注意,我假设您使用的是Python 2(否则您的第一个示例将无法正常工作)。 In Python 3 range() doesn't produce a list; 在Python 3中, range()不会产生列表。 you'd have to use the list() function to convert it to one: 您必须使用list()函数将其转换为一个:

years = list(range(2010, 2016)) + [0]
years = [0] + list(range(2010, 2016))

append and extend operations on lists do not return anything (return just None ). 对列表执行appendextend操作不会返回任何内容(仅返回None )。 That is why years is not the list you expected. 这就是为什么years不是您期望的列表。

In Python 3 range returns an instance of the range class and not a list. 在Python 3中, range返回range类的实例而不是列表。 If you want to manipulate the result of range you need a list, so: 如果要操纵range的结果,则需要一个列表,因此:

years = list(range(2010,2016)) 
years.append(2016)

Finally, (and similarly to the append above) extend operates on the list you're calling it from rather than returning the new list so: 最后,(和上面的附录类似),extend在您从其调用的列表上进行操作,而不是返回新列表,因此:

years = list(range(2010,2016))
years.extend( list(range(2016,2020)))

*While Python 2's range function does return a list, the above code will still work fine in Python 2* *虽然Python 2的range函数确实返回了一个列表,但是上面的代码在Python 2中仍然可以正常工作*

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM