在Python中将多列的列表排列到矩阵中

时间:2014-06-02 13:58:25

标签: python text-processing

我有一组表格中的数据:

#stirst block

1 6 11 

2 7 12

3 8 13

4 9 14

5 10 15 ...

#second block

17 22 27 

18 23 28

19 24 29

20 25 30

21 26 31 ...

#对于任意多个块

其中每个块不一定具有相同的列数,但每个块中的列长度相同,比如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 ...

如果可以澄清这个问题,请告诉我,并提前感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

我认为你是从文件或列表中带来的

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)

列表:

a=[[1,2,3],[2,3,4],[3,4,5]]
b=[[1,2,3],[2,3,4],[3,4,5]]
output=[]
for i,j in zip(a,b):
    output.append(i+j)
print output

#[[1, 2, 3, 1, 2, 3], [2, 3, 4, 2, 3, 4], [3, 4, 5, 3, 4, 5]]

答案 1 :(得分:0)

我不知道您是否从文件中读取了数字块。但只是假设你已经拥有了 数据。

并且假设结果块的列数无关紧要,这里的问题是保持数字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)

答案 2 :(得分:0)

此回复延伸了Raydel Miranda接受的答案。我需要能够将任意数量的块组织成所描述的矩阵形式,所有这些块都在同一个文件中。为此,请考虑单独的文件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中定义的所有块变量的列表。