在Python中,将多个列的列表排列成一个矩阵

2024-05-20 19:23:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组表格中的数据:

#第一个街区

1 6 11 

2 7 12

3 8 13

4 9 14

5 10 15 ...

第二块

^{pr2}$

#对于任意多个块,依此类推

其中每个块不一定有相同数量的列,但每个块中的列长度是相同的,比如N long,因此在这种情况下N=5。如何排列列块列表,使结果看起来像:

1 6 11 17 22 27

2 7 12 18 23 28

3 8 13 19 24 29

4 9 14 20 25 30

5 10 15 21 26 31 ...

请让我知道这个问题是否可以澄清,并提前感谢你的帮助!在


Tags: 数据列表数量情况long表格pr2列块
3条回答

这一回应扩展了雷德尔·米兰达的公认答案。我需要能够组织任意数量的块,所有这些块都在同一个文件中,形成所描述的矩阵形式。为此,考虑一个单独的文件block_defenitions.py,其中一些块被定义为变量。然后,我调整了已接受的答案代码,使其能够从文件中获取总块数,并将其格式化为所需的矩阵,并将该矩阵写入输出文件:

 def format():
    import block_definitions 

    all_numbers = []

    new_block = []

    rows = len(block_definitions.block_1)

    blocks = block_definitions.blocks


    for i in range(0,len(blocks)):
        for row in blocks[i]:
            all_numbers.extend(row)

    matrix = []

    for i in range(0,len(all_numbers), rows):
        matrix.append(all_numbers[i:i+rows])

    for i in range(len(matrix[0])):
        r = []
        for j in range(len(matrix)):
            r.append(matrix[j][i])
        new_block.append(r)

    with open("final_output.txt",'w') as output:
        output.write(str(matrix))
    output.close()

注意,blocksblock_definitions.py中定义的所有块变量的列表。在

我不知道你是不是从文件里读到了数字块。但假设你已经有了 数据。在

另外,假设结果块的列数无关,这里的问题是保持数量N。正确的?在

block_1 = [
    [1, 6, 11],
    [2, 7, 12],
    [3, 8, 13],
    [4, 9, 14],
    [5, 10, 15]
]

block_2 = [
    [17, 22, 27],
    [18, 23, 28],
    [19, 24, 29],
    [20, 25, 30],
    [21, 26, 31]
]

all_numbers = []

new_block = []

rows = len(block_1) # Since the column length is the same. 
                    # Either block_1 or block_2 works here.

# Get all numbers and sort.
for row in block_1:
    all_numbers.extend(row)

for row in block_2:
    all_numbers.extend(row)

all_numbers.sort()

# Build the matrix.
matrix = []
for i in range(0, len(all_numbers), rows):
    matrix.append(all_numbers[i:i+rows])

# Set the correct place for collumns.
for i in range(len(matrix[0])):
    r = []
    for j in range(len(matrix)):
        r.append(matrix[j][i]) 
    new_block.append(r)

print(new_block)

我认为你是从档案或名单中找来的

with open('file1.txt','r') as data1:
    a=data1.readlines()
with open('file2.txt','r') as data2:
    b=data2.readlines()

# if list just intialize them to a,b
with open('output.txt','a') as out:
    for i,j in zip(a,b):
        out.write(i+" "+j)

对于列表:

^{pr2}$

相关问题 更多 >