有效地读取空格分隔的整数

时间:2014-07-03 12:38:12

标签: python performance python-3.x user-input

有更有效的方法吗?

>>> input_list = list(map(int, input().split()))
13 4 56 75 22 3
>>> input_list
[13, 4, 56, 75, 22, 3]

1 个答案:

答案 0 :(得分:1)

从您的评论中我收集到您关注内存使用,并且您希望避免创建临时列表。不幸的是,Python没有string.split(AFAIK)的迭代器版本,但你可以使用re.finditer:

[int(match.group(0)) for match in re.finditer(r'\w+', input())]

但除非你的输入长达数兆字节,否则真的不需要担心内存并使代码复杂化。

相关问题