简体   繁体   English

为什么在尝试附加Python时我的列表没有加入

[英]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.

相关问题 为什么添加新列表后数组中的所有列表都会更改? - Why do all the lists in my array change when I append a new list? 为什么我的按钮在我重新打开时重复(python tkinter) - why are my buttons duplicating when i reopen them (python tkinter) 为什么我不能附加 2 个列表然后另存为变量然后在 python 中打印? - Why can't I append 2 lists then save as a varible then print in python? 为什么当我尝试检查我的 Python 版本时只得到“Python”? - Why do I only get 'Python' when I try to check my Python version? 当我使用 append 时,值将覆盖 python 列表中的相同值 - Values are overriding to same values in python lists when I use append 尝试进行API调用时,为什么我的python脚本停止执行? - Why does my python script stop executing when I try to make my API call? 尝试通过解释器运行Python脚本时,为什么会出现“ ImportError:未命名模块”的提示? - Why do I get “ImportError: No module named” when I try to run my Python script via the Interpreter? 为什么当我尝试阅读我的文件内容时会删除它? 打开 function python - Why is content of my file deleted when i try to read it? open function python 我无法弄清楚为什么我的 python 脚本可以运行,但是当尝试使其成为可执行文件时它不起作用 - I can't figure out why my python script works but when try to make it an executable it does not work 当我尝试使用 OOP 和类时,为什么我的代码在 python 中显示 NameError? - Why does my code show NameError in python when I try to use of OOP and classes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM