[英]Why my lists are not Joining When I try to Append Them Python
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
My CSV file has columns for Song, Artist, Year, Tempo, Hotness, Duration, Key, Loudness, Mode. 我的CSV文件具有“歌曲”,“艺术家”,“年份”,“节奏”,“热度”,“持续时间”,“调”,“响度”,“模式”等列。 I made an empty list and I am trying to append all of the float values that represent Tempo into this list, but I keep just getting a bunch of separate list values that represent each float. 我做了一个空列表,我试图将所有代表Tempo的float值添加到此列表中,但我一直只得到一堆代表每个float的独立列表值。 It seems like nothing was actually appended to p. 似乎实际上没有任何内容附加到p。 I even tried flattening the result with a function I made a while back, but it didn't have any effect. 我什至尝试使用前一阵子的功能来使结果平坦,但是没有任何效果。 Any suggestions? 有什么建议么?
for tempo in data:
p=[]
p.append(tempo[3])
doesn't make sense since p
is reset every time in the loop. 这是没有道理的,因为每次循环都会重置p
。 So move the init of p
before the loop. 因此将p
的init移到循环之前。
Better yet: use a list comprehension to avoid such bugs: 更好的是:使用列表理解来避免此类错误:
p = [tempo[3] for tempo in data]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.