如何在Python

时间:2015-04-22 09:33:02

标签: python

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

=
IF (
    CALCULATE (
        COUNTROWS ( DetailsTable ),
        DetailsTable[Dept] = "HBG"
    )
        > 0,
    1,
    0
)

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

#!/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]

TypeError:列表索引必须是整数,而不是元组

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

1 个答案:

答案 0 :(得分:5)

要使用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]