在Python中;如何在'for循环'中跳过无效值?

0 投票
3 回答
9770 浏览
提问于 2025-04-18 03:38

我有一个 for 循环,用来从一个 .csv 文件中读取 X 和 Y 的值,进展还不错。

不过,这个 .csv 文件有 65,000 行!而且大约有 2000 行是空白的。

我该怎么告诉这个 for 循环跳过空白行,直接获取下一组值呢?

我试着用 'continue' 这样做……

for line in lines:
    #split the content of each line to an array delimited by a comma ,
    pos = [x.strip() for x in line.split(',')]
    if pos == "":
        continue
    else:            
        #set up variables
        x = float(pos[0])*10000
        y = float(pos[1])*10000
        z = 0.0

但是不管用什么方法,一到第一行空白的地方,它就开始给我加零,接下来的值也都是零,还出现了这个错误信息……

ValueError: empty string for float()

我试过在 Python 导入之前先在 Apple Numbers 中删除空白行,但显然,像删除空白行这么简单的事在 Numbers 中真是太麻烦了。

我也尝试在 For 循环之前把所有空白的变量去掉,但也没能成功。

如果能给我一些简单的建议,我会非常感激!(我对这些东西还很陌生,复杂的代码我根本看不懂)。

3 个回答

0

从这个错误信息来看:ValueError: empty string for float(),我可以推测“空白行”指的是像'1, ,'这样的情况。也就是说,如果你的一行中的前两个字段有任何一个是空的(只包含空格),就会出现错误:

for line in lines:
    try:
        x, y = map(float, line.split(',')[:2])
    except ValueError:
        continue # skip invalid (for whatever reason) lines
    else:
        # use x, y here
        x *= 10000
        y *= 10000
        z = 0.0
        print(x, y, z)

示例

1,2
# the next line is blank AND IT IS SUCCESSFULLY SKIPPED NO 0,0

# missing second field
70,
# both empty
,
# first empty
,0
# 
,,80,90
3,4

输出

(10000.0, 20000.0, 0.0)
(30000.0, 40000.0, 0.0)
0

我刚开始学Python,但我觉得你可以试试下面的代码。我的想法是,如果有空行,那么这一行的长度应该是0。谢谢!

 if not line:
       continue
3

在这个相等检查中,pos 不再是一个字符串,而是变成了一个列表。

所以你可以检查这一行是否为空:

for line in lines:
    if line.strip() == "":
        continue
    #split the content of each line to an array delimited by a comma ,
    pos = [x.strip() for x in line.split(',') if x.strip()]
    # make sure you have x and y
    if len(pos) < 2:
        continue
    #set up variables
    x = float(pos[0])*10000
    y = float(pos[1])*10000
    z = 0.0

通过在定义 pos 时添加一个 if 条件,我们现在可以过滤掉空的元素。

撰写回答