简体   繁体   English

Python - 关于使用 [None] 与仅使用 [] 初始化列表的问题

[英]Python - Question about initialising lists with [None] versus with just []

I'm currently looping over some lists of strings to populate a new list.我目前正在遍历一些字符串列表以填充新列表。 Originally I had:原来我有:

z_locations = ['50', '100', '150', '250', '500']
path = [None]
for counter, value in enumerate(z_locations):
   path.append('Desktop/Data/z_' + value)

My list path would come out as a list of length 6, with the first element in my new list path would be simply NoneType .我的列表path将作为长度为 6 的列表出现,我的新列表path的第一个元素将只是NoneType I can fix this by changing to:我可以通过更改为:

z_locations = ['50', '100', '150', '250', '500']
path = []
for counter, value in enumerate(z_locations):
   path.append('Desktop/Data/z_' + value)

Which removes the NoneType being the first element and only copies as I had originally intended.它删除了作为第一个元素的NoneType并且只按照我最初的意图进行复制。 However, I am unsure why this was happening in the first place.但是,我不确定为什么会发生这种情况。 I have not encountered this NoneType before in creating new lists.在创建新列表之前,我还没有遇到过这种NoneType Could someone please enlighten me as to why this happens?有人可以请教我为什么会发生这种情况吗?

Thanks.谢谢。

That is happening because append adds an element to the end of the list.发生这种情况是因为append在列表的末尾append了一个元素。 Your list all ready has None in it so any elements you add are going to be put after it, like this [None, ...] .您准备好的列表中包含None ,因此您添加的任何元素都将放在它之后,例如[None, ...] Therefore when you get the first element, it gives you None .因此,当您获得第一个元素时,它会给您None

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

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