gpt4 book ai didi

python - 如何从文件中读取数字(用空格分隔)?

转载 作者:行者123 更新时间:2023-12-01 00:58:56 28 4
gpt4 key购买 nike

我使用的是 Python 3,并且我有一个以下形式的文件:27 4 390 43 68 817 83

如何读取这些数字?

最佳答案

您需要遍历文件的每一行,通过空格分割从行中提取所有数字,然后将这些数字附加到列表中。

numbers = []

#Open the file
with open('file.txt') as fp:
#Iterate through each line
for line in fp:

numbers.extend( #Append the list of numbers to the result array
[int(item) #Convert each number to an integer
for item in line.split() #Split each line of whitespace
])

print(numbers)

所以输出看起来像这样

[27, 4, 390, 43, 68, 817, 83]

关于python - 如何从文件中读取数字(用空格分隔)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55978736/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com