python - 如何在 Python 中从文件中读取整数
问题描述
所以我有一个看起来像这样的文件
2
3
1 2 3 4 5 6
所以我需要在三个单独的变量中读取这个文件。对于前两个我使用这样的东西:
guests = int(input_file.readline())
length = int(input_file.readline())
但是对于第三行我需要一个列表,如何将其转换为整数,我试过这个:
sticks = input_file.readline()
sticks = [int(i) for i in sticks]
但这给了我一个错误:invalid literal for int() with base 10
解决方案
您需要用于split()
读取一行上的多个整数
sticks = [int(i) for i in sticks.split()]
推荐阅读
- reactjs - 隐藏时如何使用react-spring为div制作动画?
- python - 当 2 个单元格在另一个数据框中显示相同时选择行
- javascript - npm start 在 cmd 中不起作用,并且显示错误,如图所示?
- sql - 如何一次将所有表列设置为 NOT NULL?
- python - 为什么 \0 在 Python 正则表达式替换中不起作用,即使用 sub() 或 expand(),而 match.group(0) 和 \1, \2, ...?
- makefile - 将先决条件扩展推迟到目标扩展之后
- python - Django / Python字符串保存在模型中时保持空格数
- time - 是否有其他解决方案按过滤日期计算数据而没有“with”子句?
- apache-spark - Spark Streaming 应用程序启动时如何收到通知?
- excel - 将两个字符串连接到一个单元格中