具有以下输入列表,其中包含从k = 0到4的值:
vector_input= [(3, 3, 3, 3, 3), (0, 0, 1), (3, 4, 3, 3, 4, 4), (1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 3, 3, 3, 1, 1, 3), (0, 0), (4, 4, 4, 4, 4), (1, 1), (3, 3), (1, 4, 3, 2), (3, 3, 4, 4, 4), (4, 4, 4, 4, 4), (3,), (2, 2), (2, 2, 2, 2, 2, 2), (0, 0, 0, 0, 1, 0), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (0, 0, 0, 0, 0, 0, 1, 0, 0, 1)]
我想将此列表转换为维度为k(k = 4)的频率输出列表,以便获得如下列表输出:
vector_output=[
[0,0,0,5,0],[2,1,0,0,0],[0,0,0,3,3],[0,4,0,0,0],[0,16,0,0,0], [0,3,0,4,0],
[2,0,0,0,0],[0,0,0,0,5],[0,0,0,3,0],[0,0,2,0,0],[0,0,6,0,0],[5,1,0,0,0],[0,5,0,0,0],[0,5,0,0,0],[8,2,0,0,0]]
例如:(3,3,3,3,3)变为(0,0,0,5,0)因为三次重复五次而0,1,2,4次重复。
答案 0 :(得分:1)
您可以创建分发函数:
def distribution(vector, highest=5):
dist = [0] * highest
for i in vector:
dist[i] += 1
return dist
并将其应用于具有列表理解的每个向量:
vector_input= [(3, 3, 3, 3, 3), (0, 0, 1), (3, 4, 3, 3, 4, 4), (1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 3, 3, 3, 1, 1, 3), (0, 0), (4, 4, 4, 4, 4), (1, 1), (3, 3), (1, 4, 3, 2), (3, 3, 4, 4, 4), (4, 4, 4, 4, 4), (3,), (2, 2), (2, 2, 2, 2, 2, 2), (0, 0, 0, 0, 1, 0), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (0, 0, 0, 0, 0, 0, 1, 0, 0, 1)]
print([distribution(v) for v in vector_input])
# [[0, 0, 0, 5, 0], [2, 1, 0, 0, 0], [0, 0, 0, 3, 3], [0, 4, 0, 0, 0], [0, 16, 0, 0, 0], [0, 3, 0, 4, 0], [2, 0, 0, 0, 0], [0, 0, 0, 0, 5], [0, 2, 0, 0, 0], [0, 0, 0, 2, 0], [0, 1, 1, 1, 1], [0, 0, 0, 2, 3], [0, 0, 0, 0, 5], [0, 0, 0, 1, 0], [0, 0, 2, 0, 0], [0, 0, 6, 0, 0], [5, 1, 0, 0, 0], [0, 5, 0, 0, 0], [0, 5, 0, 0, 0], [8, 2, 0, 0, 0]]
答案 1 :(得分:0)
你可以试试这个:
import itertools
vector_input= [(3, 3, 3, 3, 3), (0, 0, 1), (3, 4, 3, 3, 4, 4), (1, 1, 1, 1), (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (1, 3, 3, 3, 1, 1, 3), (0, 0), (4, 4, 4, 4, 4), (1, 1), (3, 3), (1, 4, 3, 2), (3, 3, 4, 4, 4), (4, 4, 4, 4, 4), (3,), (2, 2), (2, 2, 2, 2, 2, 2), (0, 0, 0, 0, 1, 0), (1, 1, 1, 1, 1), (1, 1, 1, 1, 1), (0, 0, 0, 0, 0, 0, 1, 0, 0, 1)]
full_listing = list(set(itertools.chain(*vector_input)))
final_data = [tuple(list(b).count(c) for c in range(min(full_listing), max(full_listing)+1)) for b in vector_input]
输出:
[(0, 0, 0, 5, 0), (2, 1, 0, 0, 0), (0, 0, 0, 3, 3), (0, 4, 0, 0, 0), (0, 16, 0, 0, 0), (0, 3, 0, 4, 0), (2, 0, 0, 0, 0), (0, 0, 0, 0, 5), (0, 2, 0, 0, 0), (0, 0, 0, 2, 0), (0, 1, 1, 1, 1), (0, 0, 0, 2, 3), (0, 0, 0, 0, 5), (0, 0, 0, 1, 0), (0, 0, 2, 0, 0), (0, 0, 6, 0, 0), (5, 1, 0, 0, 0), (0, 5, 0, 0, 0), (0, 5, 0, 0, 0), (8, 2, 0, 0, 0)]