>>> import re
>>> num_list = map(int, re.findall(r'\d+', open("circles.dat", "r").read()))
[200, 200, 100, 75, 200, 15, 325, 200, 15, 200, 75, 10, 200, 325, 10]
使用.read()
代替.readlines()
为read()返回整个文件的内容作为一个字符串(可以与正则表达式一起使用),而不像readlines()返回字符串列表。
获取数字列表(以字符串形式)后,使用map()
函数将列表类型转换为int
类型。
步骤解释:
>>> import re
>>> file_content = open("circles.dat", "r").read() # Read file as single string
>>> num_list = re.findall(r'\d+', file_content) # Fetch all numbers from string
>>> num_list
['200', '200', '100', '75', '200', '15', '325', '200', '15', '200', '75', '10', '200', '325', '10']
>>> map(int, num_list) # Typecast list of str to list of int
[200, 200, 100, 75, 200, 15, 325, 200, 15, 200, 75, 10, 200, 325, 10]
你应该读行线和解析这些线路。 – RafaelC
你想要一个长整数列表,还是列表列表? – zondo
用于删除\ t和\ n的东西,使用eval() – JustDucky