[英]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. 在此循环之外,我希望分配一个变量,例如x,以便提供以下输出。
['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. 完成此操作后,这是我应该做的:在下一步中,我想在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' 说x [2]告诉我'G'是否不同于'T','G'是否不同于'C',以及'T'是否不同于'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: 您可以轻松创建x
而无需使用numpy
或其他外部模块:
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]
. 例如, 'G'
在x[2][0]
。 You can compare it to any other cell in x
using the same notation. 您可以使用相同的符号将其与x
中的任何其他单元格进行比较。
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 编辑关于每行的注释
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.