简体   繁体   中英

How to make a list of lists in Python?

Assume,

range(len(column)) = 4
column = ['AAA', 'CTC', 'GTC', 'TTC']
for i in range(len(column)):
    a = list(column[i])

Outside of this loop I want a variable,say x to be assigned such that it gives the following output.

 ['A', 'A', 'A']
 ['C', 'T', 'C']
 ['G', 'T', 'C']
 ['T', 'T', 'C']

After doing this, here is what I should be able to do: In the Next, I want to compare within x. Say x[2] to tell me if 'G' is different from 'T' and if 'G' is different from 'C' and if 'T' is different from 'C'

I believe you are in need of a list of lists

Code:

column = ['AAA', 'CTC', 'GTC', 'TTC']
x=[]
for i in range(len(column)):
    a = list(column[i])
    x.append(a)

print x

Output:

[['A', 'A', 'A'], ['C', 'T', 'C'], ['G', 'T', 'C'], ['T', 'T', 'C']]

It's not completely clear what kind of comparison you want to do once you've formatted your data, but this is something

import numpy as np

alt_col = [list(y) for y in column]
x = np.asarray(alt_col)

you can then compare whatever you want within the array

print all(x[1, :] == x[2, :])

You can easily create x without using numpy or other external module:

column = ['AAA', 'CTC', 'GTC', 'TTC']
x = [list(column[i]) for i in range(len(column))]
print(x)

Output:

[['A', 'A', 'A'], ['C', 'T', 'C'], ['G', 'T', 'C'], ['T', 'T', 'C']]

To use this you'll need to two indices: Which you can think of as the first representing the row and the second the column. For example the 'G' is in x[2][0] . You can compare it to any other cell in x using the same notation.

inputs = ['ABC','DEF','GHI'] # list of inputs
outputs = [] # creates an empty list to be populated
for i in range(len(inputs)): # steps through each item in the list
    outputs.append([]) # adds a list into the output list, this is done for each item in the input list
    for j in range(len(inputs[i])): # steps through each character in the strings in the input list
        outputs[i].append(inputs[i][j]) # adds the character to the [i] position in the output list

outputs
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]

edit added comments as to what each line is doing

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