本文介绍了Python 转换矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的列表:

I have a list looking like this:

[2, 1, 3, 1, 2, 3, 1, 2, 2, 2]

[2, 1, 3, 1, 2, 3, 1, 2, 2, 2]

我想要的是一个转换矩阵,它向我显示如下序列:

What I want is a transition matrix which shows me the sequence like:

  • 一个 1 后面跟着一个 1 的频率
  • 一个 1 后面跟着一个 2 的频率
  • 一个 1 后面跟着一个 3 的频率

  • How often is a 1 followed by a 1
  • How often is a 1 followed by a 2
  • How often is a 1 followed by a 3

一个 2 后面跟着一个 1 的频率

How often is a 2 followed by a 1

等等...

((0,2,1), (1,2,1), (2,0,0))

((0,2,1), (1,2,1), (2,0,0))

有没有预制模块去拿这个?

Is there a premade module go get this?

推荐答案

我不知道是否有模块,但我会使用这段代码,它很容易推广:

I don't know if there's a module, but I'd go with this code, which is easily generalizeable:

import numpy as np
from collections import Counter
a = [2, 1, 3, 1, 2, 3, 1, 2, 2, 2]
b = np.zeros((3,3))
for (x,y), c in Counter(zip(a, a[1:])).iteritems():
    b[x-1,y-1] = c
print b
array([[ 0.,  2.,  1.],
       [ 1.,  2.,  1.],
       [ 2.,  0.,  0.]])

没有安装numpy:

b = [[0 for _ in xrange(3)] for _ in xrange(3)]
for (x,y), c in Counter(zip(a, a[1:])).iteritems():
    b[x-1][y-1] = c

print b
[[0, 2, 1], [1, 2, 1], [2, 0, 0]]

如果需要,一些正在发生的事情的细节:

A few details of what's going on, if needed:

  1. zip(a, a[1:]) 获取所有连续数字对.
  2. Counter 计算每对出现的次数
  3. for 循环简单地将Counter 生成的字典转换为您请求的矩阵/列表列表
  1. zip(a, a[1:]) gets all the pairs of consecutive numbers.
  2. Counter counts how many times each pair appears
  3. The for loop simple converts the dictionary Counter produces into the matrix / list of lists you requested

这篇关于Python 转换矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 18:12