Python3 ValueError: too many values to unpack with for loop

Python3 ValueError: too many values to unpack with for loop

我看到周围有人问过同样的问题,但问题总是类似:

val1, val2 = input("Enter 2 numbers")

我的问题不一样。

我有两个字符串,str1str2。我想逐字节比较它们,这样输出看起来像这样:

str1  str2
 0A    0A
 20    20
 41    41
 42    42
 43    43
 31    31
 32    32
 33    33
 2E    21

所以,我尝试了各种语法来比较它们,但它总是以相同的错误结束。这是我最近的尝试之一:

#!/usr/bin/python3
for c1, c2 in (tuple("\n ABC123."), tuple("\n ABC123!")):
    print("%02X    %02X" % (ord(c1), ord(c2)))

错误:

$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
ValueError: too many values to unpack (expected 2)

当然是这一行:

for c1, c2 in (tuple("\n ABC123."), tuple("\n ABC123!")):

经历了许多不同的迭代:

for c1, c2 in "asdf", "asdf"
for c1, c2 in list("asdf"), list("asdf")
for c1, c2 in tuple("asdf"), tuple("asdf")
for c1, c2 in (tuple("asdf"), tuple("asdf"))
for (c1, c2) in (tuple("asdf"), tuple("asdf"))

所有这些都抛出相同的错误。

我认为我不太了解 python 的 zipping/unzipping 语法,我正准备一起破解低级解决方案。

有什么想法吗?

好的,所以我最终这样做了:

for char in zip(s1,s2):
    print("%02X    %02X" % ( ord(char[0]), ord(char[1]) ))

但是,我注意到如果我碰巧有两个不同长度的列表,较长的列表似乎在末尾被截断了。例如:

s1 = "\n ABC123."
s2 = "\n ABC123!."
0A    0A
20    20
41    41
42    42
43    43
31    31
32    32
33    33
2E    21
#     !! <-- There is no "2E"

所以我想我可以通过为每个字符串打印 len() 来解决这个问题,然后填充较短的字符串以满足较长的字符串。