日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python文件按行读取变为嵌套列表_迭代两个嵌套的2D列表,其中list2具有list1的行号...

發布時間:2025/3/15 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

print

或者如果您不想安裝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,)

第二個代碼的說明(無數字):[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):中,已經有了指定行中預期的按列迭代的元素!在

要應用公式,只需將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的行号...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。