Search code examples
pythonlistmaya

Grabbing values from within a list of string arrays?


How do you select/grab the values within a list of string arrays?

When I execute a code to read the contents in my files, it is as follows:

for line in testFile:
test = line.split()

#Output:
['1', '21', '32', '43', '54', '65', '76', '87']
['2', '31', '42', '53', '64', '75', '86', '97']
['3', '41', '52', '63', '74', '85', '96', '107']
...
...

However, now supposedly I would like to select and grab the first values - 1,2,3 in the output only, I got ['1', '21', '32', '43', '54', '65', '76', '87'] or the values of the last line, should I code it print test[0] or for item in test..

Meaning to say, if I decided to grab the values of column 3, it will gives me 32,42,52, and if I grab column 6, it will gives me 65,75,85 etc The number of columns are the same through and I asked this because I am either going to set the values in the rotation/translation attibutes while the first column being the frame number...

Is it possible to do so?


Solution

  • You just need to transpose the contents, with zip function, like this

    with open("inputfile") as f:
        rows = zip(*[line.split() for line in f])
    
    print rows[0]
    

    We open the file with open and the with statement. Then, we read line by line and split every read line. So, we get a list of lists. Now, we apply each of those lists to zip function, which actually transposes them. After transposing, the rows become columns and the columns become rows. For example,

    [[1, 2, 3]
     [4, 5, 6]
     [7, 8, 9]]
    

    will become

    [[1, 4, 7]
     [2, 5, 8]
     [3, 6, 9]]