日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

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

發(fā)布時(shí)間:2025/3/15 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python文件按行读取变为嵌套列表_迭代两个嵌套的2D列表,其中list2具有list1的行号... 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

您可以使用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,下面是您可以做的(實(shí)際上這是您想要的):

^{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,)

第二個(gè)代碼的說(shuō)明(無(wú)數(shù)字):[dataset2D[row_idx] for row_idx in row_indices]

這基本上是將每一行(dataset2D[row_idx])作為一個(gè)列表整理在一起。所以這個(gè)表達(dá)式的結(jié)果是一個(gè)列表列表(來(lái)自指定的行索引)for column in zip(*rows):

然后zip(*rows)將按列迭代(您想要的那個(gè))。這是通過(guò)獲取每行的第一個(gè)元素,然后將它們組合在一起形成一個(gè)tuple。在每次迭代中,結(jié)果存儲(chǔ)在變量column中。在

那么在for column in zip(*rows):中,已經(jīng)有了指定行中預(yù)期的按列迭代的元素!在

要應(yīng)用公式,只需將print column,改成你想做的事情。例如,我修改代碼以包含行和列號(hào):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)

這將導(dǎo)致: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

我希望這有幫助。在

總結(jié)

以上是生活随笔為你收集整理的python文件按行读取变为嵌套列表_迭代两个嵌套的2D列表,其中list2具有list1的行号...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。