在Python中读取文件中的整数可以通过以下几种方法实现:
1. 使用正则表达式:
import refilename = 'CP_epoch264.pth'regex = re.compile(r'\d+')numbers = [int(x) for x in regex.findall(filename)]print(max(numbers)) 如果文件名中只有一个数字,则使用max函数取最大值
2. 使用`input()`函数和`eval()`函数:
用户输入包含数字的字符串,例如 "1 2 3"user_input = input("请输入数字,用空格分隔:")numbers = list(map(int, user_input.split()))print(numbers)
3. 使用`open()`函数和`numpy`库:
import numpy as npwith open('in.txt', 'r') as f:rows, cols = np.fromfile(f, dtype=int, count=2, sep=' ')data = np.fromfile(f, dtype=int, count=cols*rows, sep=' ').reshape((rows, cols))print(data)
4. 使用`open()`函数和`map()`函数:
with open('in.txt', 'r') as f:data = []cols, rows = map(int, f.readline().split())for i in range(0, rows):data.append(list(map(int, f.readline().split()[:cols])))print(data)
请根据您的具体需求选择合适的方法。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/96205.html