python中numpy矩阵重排列是按行还是按列

Python029

python中numpy矩阵重排列是按行还是按列,第1张

Numpy可以使用reshape()函数进行矩阵重排列,默认按行排列(C语言风格),通过修改order参数可以改为按列排列(Fortran风格)。参考例子:

In [1]: import numpy as np

In [2]: a = np.array([[1,2,3],[4,5,6]])

In [3]: print a

[[1 2 3]

 [4 5 6]]

In [4]: b = a.reshape((3,2)) # 默认按行排列

In [5]: print b

[[1 2]

 [3 4]

 [5 6]]

In [6]: c = a.reshape((3,2),order='F') # 改为Fortran风格的按列排列

In [7]: print c

[[1 5]

 [4 3]

 [2 6]]

这个代码很简单

#!/usr/bin/env python3

data = dict()

# process a.txt

for line in open("a.txt", "r"):

    k, s, v = line.partition("_")

    if s != "_":

        continue

    data[k.strip()] = v.strip()

# generate c.txt

fd = open("c.txt", "w")

for line in open("b.txt", "r"):

    line = line.strip()

    if len(line) == 0:

        fd.write("\n")

        continue

    fd.write("{}_{}\n".format(line, data[line]))

fd.close()

按照你的要求编写的Python程序如下(这是4个字符取2个字符,如果要取3个字符,请把repeat参数的值由2改成3)

import itertools

print([''.join(i) for i in itertools.product("abcd",repeat=2)])

运行结果

['aa', 'ab', 'ac', 'ad', 'ba', 'bb', 'bc', 'bd', 'ca', 'cb', 'cc', 'cd', 'da', 'db', 'dc', 'dd']