如何在 Python 3 中读取下一个整数而忽略空格?有没有办法制作一个从空格分隔的整数流中返回整数的生成器?
我拥有的最好的就是这个:
def ints():
while True:
yield from (int(x) for x in input().split())
最佳答案
完全忽略空格并从文件中读取(将整数纯粹视为连续数字):
import mmap
import re
with open('somefile', 'rb') as fin:
mf = mmap.mmap(fin.fileno(), 0, access=mmap.ACCESS_READ)
for digits in re.finditer('(\d+)', mf):
print(digits.group(1))
或者,如果您已经将所有内容都包含在字符串中,则适本地调整finditer
,也许类似于:
yield from (match.group(1) for match in re.finditer('\d+', some_string))
关于python - 如何在Python中忽略空格读取下一个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19504749/