简体   繁体   中英

TypeError: list indices must be integers, not tuple

My code:`

#!/usr/bin/python

with open("a.dat", "r") as ins:
    array = []
    for line in ins:
        l=line.strip()
        array.append(l)

a1 = array[:,1]
print a1

I want to read a.dat as array then take the first column.What is wrong?

For loading numerical data, it's often useful to use numpy instead of just Python.

import numpy as np
arr = np.loadtxt('a.dat')
print arr[:,0]

numpy is a Python library that's very well suited to loading and manipulating numerical data (with a bonus that when used correctly, it's waaaay faster than using Python lists). In addition, for dealing with tabular data with mixed datatypes, I recommend using pandas .

import pandas as pd
df = pd.load_csv('a.dat', sep=' ', names=['col1', 'col2'])
print df['col1']

Numpy can be found here

Pandas can be found here

This is wrong: a1 = array[:,1] putting values separated with comma make it a Tuple of 2 values. You should use:

a1 = array[0]

To get first row or to get first column use:

column = [row[0] for row in array]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM