gpt4 book ai didi

python - 如何在Python中读取数组的第一行

转载 作者:行者123 更新时间:2023-12-02 08:19:22 25 4
gpt4 key购买 nike

我是Python学习新手,这是我当前的代码:

#!/usr/bin/python

l = []
with open('datad.dat', 'r') as f:
for line in f:
line = line.strip()
if len(line) > 0:
l.append(map(float, line.split()))
print l[:,1]

我尝试这样做,但错误地使用了 FORTRAN 语法,并收到以下错误:

  File "r1.py", line 9, in <module>
print l[:,1]

类型错误:列表索引必须是整数,而不是元组

如何获取数组的第一行或第一列?

最佳答案

要打印第一行,请使用 l[0],要获取列,您需要使用 zip 进行转置 print(list(zip(*l))[0]).

In [14]: l = [[1,2,3],[4,5,6],[7,8,9]]  
In [15]: l[0] # first row
Out[15]: [1, 2, 3]
In [16]: l[1] # second row
Out[16]: [4, 5, 6]
In [17]: l[2] # third row
Out[17]: [7, 8, 9]
In [18]: t = list(zip(*l))
In [19] t[0] # first column
Out[19]: (1, 4, 7)
In [20]: t[1] # second column
Out20]: (2, 5, 8)
In [21]: t[2] # third column
Out[21]: (3, 6, 9)

csv module可能也有用:

import csv

with open('datad.dat', 'r') as f:
reader = csv.reader(f)
l = [map(float, row) for row in reader]

关于python - 如何在Python中读取数组的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29793345/

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