python - 在 for 循环中使用 str.split 时出现“ValueError 太多值无法解包”
问题描述
我在原因很明显之前就遇到了这个错误,但是我在下面的这段代码中遇到了问题。
#!/usr/bin/python
ACL = 'group:troubleshooters:r,user:auto:rx,user:nrpe:r'
for e in ACL.split(','):
print 'e = "%s"' % e
print 'type during split = %s' % type(e.split(':'))
print 'value during split: %s' % e.split(':')
print 'number of elements: %d' % len(e.split(':'))
for (one, two, three) in e.split(':'):
print 'one = "%s", two = "%s"' % (one, two)
我已经添加了这些打印语句以进行调试,并确认拆分正在生成一个 3 元素列表,但是当我尝试将其放入 3 个变量中时,我得到:
e = "group:troubleshooters:r"
type during split = <type 'list'>
value during split: ['group', 'troubleshooters', 'r']
number of elements: 3
Traceback (most recent call last):
File "/tmp/python_split_test.py", line 10, in <module>
for (one, two, three) in e.split(':'):
ValueError: too many values to unpack
我错过了什么?
解决方案
也许你应该:
one, two, three = e.split(":")
ase.split(":")
已经是具有三个值的可迭代对象。
如果你写
for (one, two, three) in something
然后something
必须是三个值的可迭代对象,例如[[1, 2, 3], [4, 5, 6]]
,但不是[1, 2, 3]
。
推荐阅读
- python - 更改 matplotlib 中图例中的标签格式
- python - 如何找出矩阵中大于某个阈值的值?
- python - 向量化 Pandas 列
- typescript - TypeScript:联合类型分布的条件类型数组
- python - 使用 ctypes 调用带有指针参数的 C++ 函数
- java - 在分布式计算期间防止死锁
- javascript - 为什么 AngularJS $onChanges 没有注意到数组发生了变化?
- android - 未找到可绘制资源,但它们存在于可绘制文件夹中
- wpf - 如何在 WPF 中编辑完整的 ToggleButton 模板的副本?缺少一些触发器
- angular - Angular 无法连接到 docker compose 中的 Spring Boot 端点