python读取txt指定内容写入数组_如何使用Python将文本文件中的数据读取到数组中...

本文探讨了如何使用Python从文本文件中读取特定格式的数据并进行回归分析。提出了两种不同的数据存储方案,并通过示例代码展示了如何实现数据读取及计算平均值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1586010002-jmsa.png

I have a bit trouble with some data stored in a text file on hand for regression analysis using Python.

The data are stored in the format that look like this:

2104,3,399900 1600,3,329900 2400,3,369000 ....

I need to do some analysis like finding mean by this:

(2104+1600+...)/number of data

I think the appropriate steps is to store the data into array. But I have no idea how to store it. I think of two ways to do so. The first one is to set 3 array that stores like

a=[2104 1600 2400 ...] b=[3 3 3 ...] c=[399900 329900 36000 ...]

The second way is to store in

a=[2104 3 399900], b=[1600 3 329900] and so on.

Which one is better?

Also, how to write code that allows the data can be stored into array? I think of like this:

with open("file.txt", "r") as ins:

array = []

elt.strip(',."\'?!*:') for line in ins:

array.append(line)

Is that correct?

解决方案

You could use :

with open('data.txt') as data:

substrings = data.read().split()

values = [map(int, substring.split(',')) for substring in substrings]

average = sum([a for a, b, c in values]) / float(len(values))

print average

With this data.txt, :

2104,3,399900 1600,3,329900 2400,3,369000

2105,3,399900 1601,3,329900 2401,3,369000

It outputs :

2035.16666667

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值