给定:
>>> txt='''\
... 3 4
... 12 14 16
... 1 2
... 3 4
... 5 6'''
如果这些行有意义,你可以这样做:
>>> [map(int, line.split()) for line in txt.splitlines()]
[[3, 4], [12, 14, 16], [1, 2], [3, 4], [5, 6]]
如果这些行没有意义,而您只想要所有数字,则可以执行以下操作:
>>> map(int, txt.split())
[3, 4, 12, 14, 16, 1, 2, 3, 4, 5, 6]
如果您的源代码中存在不能转换为整数的字符串:
>>> txt='''\
... 3 4
... 12 14 16
... 1 2
... 3 4
... 5 6
... text that won't be integers
... 99 100 101'''
你可以使用转换函数:
>>> def conv(s):
... try:
... return int(s)
... except ValueError:
... return s
...
>>> [[conv(s) for s in line.split()] for line in txt.splitlines()]
[[3, 4], [12, 14, 16], [1, 2], [3, 4], [5, 6], ['text', 'that', "won't", 'be', 'integers'], [99, 100, 101]]
或过滤掉非数字的内容:
>>> map(int, filter(lambda s: s.isdigit(), txt.split()))
[3, 4, 12, 14, 16, 1, 2, 3, 4, 5, 6, 99, 100, 101]
split(" ")
,然后遍历结果呢?在这里使用正则表达式似乎有些过度。 - skamazin[3,4,12,14, 16,...]
还是[[3, 4], [12, 14, 16], ...]
? - dawg