python文件按行读取变为嵌套列表_迭代两个嵌套的2D列表,其中list2具有list1的行号...
您可以使用Numpy(希望您不喜歡這樣):import numpy
dataset2D = [ [6, 4], [0, 0, 0, 1], [1, 0, 2, 0], [2, 2, 0, 1], [1, 1, 1, 0], [0, 0, 1, 1], [1, 0, 2, 1] ]
dataset2D_size = dataset2D[0]
dataset2D = numpy.array(dataset2D)
partition2D = [ ['A', '1', '2', '4'], ['B', '3', '5'], ['C', '6'] ]
for partition in partition2D:
label = partition[0]
row_indices = [int(i) for i in partition[1:]]
# Take the specified rows
rows = dataset2D[row_indices]
# Iterate the columns (this is the power of Python!)
for column in zip(*rows):
# Now, column will contain one column of data from specified row indices
print column, # Apply your formula here
或者如果您不想安裝Numpy,下面是您可以做的(實際上這是您想要的):
^{pr2}$
兩者都將打印:(0, 1, 1) (0, 0, 1) (0, 2, 1) (1, 0, 0)
(2, 0) (2, 0) (0, 1) (1, 1)
(1,) (0,) (2,) (1,)
第二個代碼的說明(無數(shù)字):[dataset2D[row_idx] for row_idx in row_indices]
這基本上是將每一行(dataset2D[row_idx])作為一個列表整理在一起。所以這個表達式的結果是一個列表列表(來自指定的行索引)for column in zip(*rows):
然后zip(*rows)將按列迭代(您想要的那個)。這是通過獲取每行的第一個元素,然后將它們組合在一起形成一個tuple。在每次迭代中,結果存儲在變量column中。在
那么在for column in zip(*rows):中,已經(jīng)有了指定行中預期的按列迭代的元素!在
要應用公式,只需將print column,改成你想做的事情。例如,我修改代碼以包含行和列號:print 'Processing partition %s' % label
for (col_num, column) in enumerate(zip(*rows)):
print 'Column number: %d' % col_num
for (row_num, element) in enumerate(column):
print '[%d,%d]: %d' % (row_indices[row_num], col_num, element)
這將導致:Processing partition A
Column number: 0
[1,0]: 0
[2,0]: 1
[4,0]: 1
Column number: 1
[1,1]: 0
[2,1]: 0
[4,1]: 1
Column number: 2
[1,2]: 0
[2,2]: 2
[4,2]: 1
Column number: 3
[1,3]: 1
[2,3]: 0
[4,3]: 0
Processing partition B
Column number: 0
[3,0]: 2
[5,0]: 0
Column number: 1
[3,1]: 2
[5,1]: 0
Column number: 2
[3,2]: 0
[5,2]: 1
Column number: 3
[3,3]: 1
[5,3]: 1
Processing partition C
Column number: 0
[6,0]: 1
Column number: 1
[6,1]: 0
Column number: 2
[6,3]: 2
Column number: 3
[6,3]: 1
我希望這有幫助。在
總結
以上是生活随笔為你收集整理的python文件按行读取变为嵌套列表_迭代两个嵌套的2D列表,其中list2具有list1的行号...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SVM面试题
- 下一篇: ImportError: No modu