Python 将数字追加到列表但跳过第一行:代码不起作用
我相信有一个简单的答案,但这让我发疯。我有下面的代码,它应该将数字附加到两个列表中(首先将它们转换为浮点数),但跳过第一行,因为它包含字符串。出于某种原因,“count”变量仅保持为1,而不是增加:Python 将数字追加到列表但跳过第一行:代码不起作用,python,Python,我相信有一个简单的答案,但这让我发疯。我有下面的代码,它应该将数字附加到两个列表中(首先将它们转换为浮点数),但跳过第一行,因为它包含字符串。出于某种原因,“count”变量仅保持为1,而不是增加: gdp = [] unemp = [] data = open("C:/users/EuanRitchie/unempgdp.csv") count = 1 for i in data: print count i = i.split(",") unemp.append
gdp = []
unemp = []
data = open("C:/users/EuanRitchie/unempgdp.csv")
count = 1
for i in data:
print count
i = i.split(",")
unemp.append(i[0])
gdp.append(i[1])
if count==1:
count =+ 1
elif count>1:
unemp[i] = float(unemp[i])
gdp[i] = float(gdp[i])
我知道可能有更快的方法来使用csv模块实现这一点,但这也是一种实践。显然,我需要它。要跳过iterable的第一项,请将其转换为迭代器并迭代一次:
it = iter(data)
next(it, None) # if present, skip first item
然后使用你的数据
for item in it:
# whatever
或者,您可以使用枚举
为您跟踪计数
:
for count, item in enumerate(data):
if count == 0:
continue # skip first line
# whatever
要跳过iterable的第一项,请将其转换为迭代器并迭代一次:
it = iter(data)
next(it, None) # if present, skip first item
然后使用你的数据
for item in it:
# whatever
或者,您可以使用枚举
为您跟踪计数
:
for count, item in enumerate(data):
if count == 0:
continue # skip first line
# whatever
您不是在增加计数。正确的语法是:
count+=1
而不是
count=+1
(这将始终保持count的值等于1)您不是在增加count。正确的语法是:
count+=1
而不是
count=+1
(这将始终保持count的值等于1)要忽略第一行,请读取它。另外,用将打开的文件放入中,以确保其正确关闭。我认为不需要柜台
with open("C:/users/EuanRitchie/unempgdp.csv") as f:
header = f.readline() #reads the first line
for line in f:
# Process the rest of the lines here
...
要忽略第一行,请阅读它。另外,用
将打开的文件放入中,以确保其正确关闭。我认为不需要柜台
with open("C:/users/EuanRitchie/unempgdp.csv") as f:
header = f.readline() #reads the first line
for line in f:
# Process the rest of the lines here
...
有一个输入错误:
count =+ 1
但应该是
count += 1
有一个输入错误:
count =+ 1
但应该是
count += 1
'=+'!+'+='代码>count=+1
只是count=+1
或count=1
。count+=1,而不是count=+1看起来您正在读取CSV文件-如果是这样,请查看内置的。'=+'!+'+='代码>count=+1
只是count=+1
或count=1
。count+=1,而不是count=+1看起来您正在读取CSV文件-如果是这样,请查看内置文件。感谢大家的回答,+=是一个愚蠢的错误!谢谢大家的回答,+=是个愚蠢的错误!