这是我现在的代码:
from pathlib import Path
content = Path('numbers.txt').read_text()
for i in range(len(content)):
content[i] = int(content[i])
print(content)
目前代码不起作用
拆分应该很简单,除非我误解了?
from pathlib import Path
content = Path('numbers.txt').read_text()
list_content = content.split()
integer_list = [int(x) for x in list_content]
print(integer_list)
from pathlib import Path
content = Path('numbers.txt').read_text()
listofnumbers = list(map(int, content.split()))
此代码通过将int函数映射到内容中的数字列表来工作。
编辑:我的代码中有一个错误,现在应该修复了。
遗憾的是,您不能创建一个整数列表,但可以创建一个"数字"列表。如果有效,你可以尝试以下方法:
from pathlib import Path
content = Path('numbers.txt').read_text().split(" ")
print(content)
split(" ")
将文件中的数字除以引号中的空格。然后,它将这些"拆分"中的每一个添加到一个数组中。
如果你需要把它作为一个整数,你可以使用这样的东西:
content = Path('numbers.txt').read_text().split(" ")
for n in content:
print((int(n))
# Execute your code here but use the int() method to convert it back to an integer
为此,您需要在每次拆分数字时执行代码。