在for inside for循环中使用int时文字无效

时间:2017-08-02 10:46:26

标签: python

我有一个带有一堆流十六进制数字的文件,我需要转换回整数。在读取数据并将其分成行后,我有以下内容:

In [153]: text_lines
Out[153]:
['AB01D801AC01870BB6FFE000',
 'A9015F01AB01860B2600B300',
 'A901FE00AC01860BD4FF4E01',
 'AB01E700AB01850B4200DD00',
 'AA017F01AA01850B23009E00',
 'AC017D01AE01840B08004301',
 '']

现在,如果我尝试遍历这些行,重新排列字节并进行转换,我会收到错误:

In [138]: for line in text_lines:
   .....:     phA.append(int((line[2:4]+line[0:2]),16))
   .....:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-138-eb4d5ccf5005> in <module>()
      1 for line in text_lines:
----> 2     phA.append(int((line[2:4]+line[0:2]),16))
      3

ValueError: invalid literal for int() with base 16: ''

但我可以毫无问题地做到这一点:

In [165]: for i in range(len(text_lines)-1):
   .....:     line = text_lines[i]
   .....:     print int((line[2:4]+line[0:2]),16)
   .....:
427
425
425
427
426
428

我也可以打破第一个for循环,只显示应该放入int()函数的文字,它看起来就像我期望的那样。

In [174]: for line in text_lines:
   .....:     print line[2:4]+line[0:2]
   .....:
01AB
01A9
01A9
01AB
01AA
01AC

关于为什么迭代text_lines中的行会导致int()函数中断的任何想法?感谢。

2 个答案:

答案 0 :(得分:1)

你的最后一个字符串是一个空字符串:

text_lines = ['AB01D801AC01870BB6FFE000',
 'A9015F01AB01860B2600B300',
 'A901FE00AC01860BD4FF4E01',
 'AB01E700AB01850B4200DD00',
 'AA017F01AA01850B23009E00',
 'AC017D01AE01840B08004301',
 ''] # here

并且您无法将空字符串转换为整数。

您可以在循环之前使用filter删除空字符串:

>>> text_lines = list(filter(lambda x: x != '', text_lines))
>>> text_lines
['AB01D801AC01870BB6FFE000', 'A9015F01AB01860B2600B300', 'A901FE00AC01860BD4FF4E01', 'AB01E700AB01850B4200DD00', 'AA017F01AA01850B23009E00', 'AC017D01AE01840B08004301']
>>> for line in text_lines:
...     print(int(line[2:4]+line[0:2],16))
...
427
425
425
427
426
428

答案 1 :(得分:0)

正如Irmen de Jong所提到的,摆脱列表末尾的空字符串。

摆脱空字符串的更多pythonic方法是, 通过

text_lines=filter(None,text_lines)

或者,
循环((列表理解))条件!

>>> [int(line[2:4]+line[0:2],16) for line in text_lines if line]
[427, 425, 425, 427, 426, 428]