[英]How to make a list of lists in Python?
假設,
range(len(column)) = 4
column = ['AAA', 'CTC', 'GTC', 'TTC']
for i in range(len(column)):
a = list(column[i])
在此循環之外,我希望分配一個變量,例如x,以便提供以下輸出。
['A', 'A', 'A']
['C', 'T', 'C']
['G', 'T', 'C']
['T', 'T', 'C']
完成此操作后,這是我應該做的:在下一步中,我想在x內進行比較。 說x [2]告訴我'G'是否不同於'T','G'是否不同於'C',以及'T'是否不同於'C'
我相信您需要清單清單
碼:
column = ['AAA', 'CTC', 'GTC', 'TTC']
x=[]
for i in range(len(column)):
a = list(column[i])
x.append(a)
print x
輸出:
[['A', 'A', 'A'], ['C', 'T', 'C'], ['G', 'T', 'C'], ['T', 'T', 'C']]
格式化數據后,您還不確定要進行哪種比較,但這是需要注意的
import numpy as np
alt_col = [list(y) for y in column]
x = np.asarray(alt_col)
然后,您可以比較數組中所需的任何內容
print all(x[1, :] == x[2, :])
您可以輕松創建x
而無需使用numpy
或其他外部模塊:
column = ['AAA', 'CTC', 'GTC', 'TTC']
x = [list(column[i]) for i in range(len(column))]
print(x)
輸出:
[['A', 'A', 'A'], ['C', 'T', 'C'], ['G', 'T', 'C'], ['T', 'T', 'C']]
要使用此功能,您需要兩個索引:您可以將其視為第一個代表行,第二個代表列。 例如, 'G'
在x[2][0]
。 您可以使用相同的符號將其與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']]
編輯關於每行的注釋
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.