numpy 创建重复N次而不重复本身的项目列表

ycl3bljg  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(38)

我想重复列表N次,但不重复项目本身。例如,

from itertools import *

items = [ _ for _ in range(3)]
# repeat each item twice
row = sorted(list(chain(*repeat(items, 2))))
row

[0, 0, 1, 1, 2, 2]

字符串
但是,我想创建另一个列表(col),它也有6个项目:

col = [1, 2, 0, 2, 0, 1]


这些列表的目标是创建一个对角项= 0的邻接矩阵。(COO格式是我的最终目标,所以随机。 Shuffle 不符合我的需要)

row = [0,0,1,1,2,2]
col = [1,2,0,2,0,1]
value = [1,1,1,1,1,1]

import scipy
mtx = scipy.sparse.coo_matrix((value, (row, col)), shape=(3, 3))
mtx.todense()

matrix([[0, 1, 1],
        [1, 0, 1],
        [1, 1, 0]])


我需要的信息到一个COO格式。任何建议?提前感谢!

b1payxdu

b1payxdu1#

如果你想填充一个大小为(n, m)的矩阵的 * 所有 * 非对角索引,你可以这样做:

n, m = 3, 3
value = [1,3,7,2,1,4]

row, col = np.where(np.arange(m)[:,None] != np.arange(n))
a = np.zeros((n, m), dtype=int)
a[row, col] = value

>>> a
array([[0, 1, 3],
       [7, 0, 2],
       [1, 4, 0]])

字符串
如果你只是想从COO规范中创建一个密集数组(指定行,列索引和相应的值):

n, m = 3, 3
# or, if you only have row, col: n, m = np.max(np.c_[row, col], 0) + 1

row = [0,1,2,2]
col = [1,2,0,1]
value = [1,2,3,4]

a = np.zeros((n, m), dtype=int)
a[row, col] = value

>>> a
array([[0, 1, 0],
       [0, 0, 2],
       [3, 4, 0]])

kupeojn6

kupeojn62#

因为你想创建一个对角线为0的1矩阵,所以使用numpy.identity

N = 3

out = 1 - np.identity(N, dtype=int)

字符串
输出量:

array([[0, 1, 1],
       [1, 0, 1],
       [1, 1, 0]])


如果你只想创建row/col索引:

a = np.arange(N)
row, col = np.where(a[:,None]!=a)


输出量:

# row
array([0, 0, 1, 1, 2, 2])

# col
array([1, 2, 0, 2, 0, 1])

相关问题