获取空白列表 - 不知道为什么?

时间:2011-09-08 20:25:31

标签: python list for-loop enumerate

我使用此代码:

from __future__ import division
from __future__ import print_function

in_file = open("s:/Personal Folders/Andy/Python Projects/People Cancelled/Analyze Authorize Truncated.csv")
text = in_file.readlines()
in_file.close()

header = text[0:1]
text = text[1:]

for index, line in enumerate(text):
    text[index] = line.split(",")

name = text
dates = text

for index, line in enumerate(name):
    name[index] = line[3:5]

for stuff, area in enumerate(dates):
     dates[stuff] = area[7:8]

print(name)
print(dates)

我得到了这个输出:

 [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
 [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

知道为什么吗?出于某种原因,两个for循环之间似乎存在某种干扰 - 如果我单独进行,我会得到我想要的结果。

谢谢!

1 个答案:

答案 0 :(得分:1)

看看这两行:

name = text
date = text

这些行制作名称和日期的文本副本以指向;相反,他们将名称和日期设置为文本的替代名称。因此,在第三个for循环之后(使用正文name[index] = line[3:5]text中的每一行都是两个项目(因为textname是相同的列表)。事实上,我甚至不知道为什么你最初将namedate都设置为text;只需制作namedate就可以达到预期效果等于新的空列表,并根据text向它们追加项目。