import csv
filename='songdata.csv'
reader=csv.reader(open(filename,'r'))
header=next(reader)
data=[]
for row in reader:
# row=[Song, Artist, Year, Tempo, Hotness, Duration, Key, Loudness, Mode]
Song=row[0]
Artist=row[1]
Year=int(row[2])
Tempo=float(row[3])
Hotness=float(row[4])
Duration=float(row[5])
Key=int(row[6])
Loudness=float(row[7])
Mode=int(row[8])
data.append([Song, Artist, Year, Tempo, Hotness, Duration, Key, Loudness, Mode])
for tempo in data:
p=[]
p.append(tempo[3])
print p
Run Code Online (Sandbox Code Playgroud)
我的CSV文件包含歌曲,艺术家,年份,速度,热度,持续时间,按键,响度,模式的列.我创建了一个空列表,我试图将表示Tempo的所有浮点值附加到此列表中,但我只是得到一堆代表每个浮点数的单独列表值.似乎没有任何东西实际附加到p.我甚至尝试使用我做了一段时间的功能来平滑结果,但它没有任何效果.有什么建议?
for tempo in data:
p=[]
p.append(tempo[3])
Run Code Online (Sandbox Code Playgroud)
因为p每次在循环中重置都没有意义.所以p在循环之前移动init .
更好的是:使用列表理解来避免这样的错误:
p = [tempo[3] for tempo in data]
Run Code Online (Sandbox Code Playgroud)