Python ValueError:太多的值无法用 glob 解包 [英] Python ValueError: too many values to unpack with glob

查看:54
本文介绍了Python ValueError:太多的值无法用 glob 解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加载两组 CSV 文件并对两者进行一些计算,例如每组的差异,平均绝对误差 set1 - set2 exc.

I'm trying to load two sets of CSV files and do some calculations on both such as difference of each set, mean absolute error set1 - set2 exc.

我正在尝试像这样加载两个集合:

I'm trying to load both sets like this:

import glob    
for a, b in (glob.glob("*a.csv"), glob.glob("*b.csv")):

我得到了错误:

ValueError: too many values to unpack

推荐答案

问题

您收到 ValueError 是因为您试图为元组分配的项目数超过您提供的目标变量的数量.for 循环元组解包语法将遍历元组中的每个列表,并尝试将元组中的每个值分配给目标(ab).例如,这会起作用:

The Problem

You are getting the ValueError because you are trying to assign more items to the tuple than the number of target variables you provide. The for loop tuple unpacking syntax will loop through each list in your tuple and attempt to assign each value in the tuple to your targets (a and b). For instance, this would work:

for a,b in (['0a.csv', '1a.csv'], ['0b.csv', '1b.csv']):
    print a,b

它将每个列表的第一个值分配给 a,将第二个值分配给 b.上面的代码打印:

It assigns the first value of each list to a and the second value to b. The code above prints:

0a,csv 1a.csv
0b.csv 1b.csv

因此,您会收到 ValueError,因为至少有一个 glob.glob 调用的结果是一个长度超过两个元素的列表.

Thus, you are getting the ValueError because the results from at least one of your glob.glob calls is a list longer than two elements.

根据您的尝试,我认为您想使用 zip.

Based on what you are trying to do, I think you want to use zip.

import glob

for a,b in zip(glob.glob("*a.csv"), glob.glob("*b.csv")):
    # whatever

这将获取与您提供的模式匹配的文件对,并将它们分配给 ab.例如,如果您有文件 0a.csv1a.csv2a.csv0b.csv1b.csv2b.csv

That will take pairs of files matching the pattern you gave and assign them to a and b. For example, if you have files 0a.csv, 1a.csv, 2a.csv, 0b.csv, 1b.csv, and 2b.csv doing

for a,b in zip(glob.glob("*a.csv"), glob.glob("*b.csv")):
    print a, b

结果

0a.csv 0b.csv
1a.csv 1b.csv
2a.csv 2b.csv

这篇关于Python ValueError:太多的值无法用 glob 解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆