如何将元组列表转换为矩阵?
How to convert a list of tuples to a matrix?
我有以下元组列表:
list = [(House, Dog, 7), (House, Cat, 5), (Garden, Dog, 4), (Garden, Cat, 3), (Park,Mouse,2)]
我正在寻找具有以下结构的矩阵:
result = [
['' , Dog, Cat, Mouse],
[House, 7, 5, ''],
[Garden, 4, 3, ''],
[Park, '', '', 2 ]
]
这将保持 column/row 名称的顺序并生成请求的解决方案:
from collections import OrderedDict
input = [('House', 'Dog', 7), ('House', 'Cat', 5), ('Garden', 'Dog', 4), ('Garden', 'Cat', 3), ('Park', 'Mouse', 2)]
column_names = list(OrderedDict.fromkeys(item[1] for item in input))
row_names = list(OrderedDict.fromkeys(item[0] for item in input))
result = [[''] * (len(column_names) + 1) for i in range(len(row_names) + 1)]
for i in range(len(column_names)):
result[0][i+1] = column_names[i]
for i in range(len(row_names)):
result[i+1][0] = row_names[i]
for item in input:
result[row_names.index(item[0]) + 1][column_names.index(item[1]) + 1] = item[2]
print(result)
from collections import Counter
data = [("House", "Dog", 7), ("House", "Cat", 5), ("Garden", "Dog", 4), ("Garden", "Cat", 3), ("Park", "Mouse", 2)]
header = [""]
column = [""]
counts = Counter();
for place, animal, count in data:
if animal not in header:
header.append(animal)
if place not in column:
column.append(place)
counts[(place, animal)] += count
result = [header]
for (place, animal), count in counts.items():
col = header.index(animal)
row = column.index(place)
if row >= len(result):
result.append([place] + [""] * (len(header) - 1))
result[row][col] = count
我有以下元组列表:
list = [(House, Dog, 7), (House, Cat, 5), (Garden, Dog, 4), (Garden, Cat, 3), (Park,Mouse,2)]
我正在寻找具有以下结构的矩阵:
result = [
['' , Dog, Cat, Mouse],
[House, 7, 5, ''],
[Garden, 4, 3, ''],
[Park, '', '', 2 ]
]
这将保持 column/row 名称的顺序并生成请求的解决方案:
from collections import OrderedDict
input = [('House', 'Dog', 7), ('House', 'Cat', 5), ('Garden', 'Dog', 4), ('Garden', 'Cat', 3), ('Park', 'Mouse', 2)]
column_names = list(OrderedDict.fromkeys(item[1] for item in input))
row_names = list(OrderedDict.fromkeys(item[0] for item in input))
result = [[''] * (len(column_names) + 1) for i in range(len(row_names) + 1)]
for i in range(len(column_names)):
result[0][i+1] = column_names[i]
for i in range(len(row_names)):
result[i+1][0] = row_names[i]
for item in input:
result[row_names.index(item[0]) + 1][column_names.index(item[1]) + 1] = item[2]
print(result)
from collections import Counter
data = [("House", "Dog", 7), ("House", "Cat", 5), ("Garden", "Dog", 4), ("Garden", "Cat", 3), ("Park", "Mouse", 2)]
header = [""]
column = [""]
counts = Counter();
for place, animal, count in data:
if animal not in header:
header.append(animal)
if place not in column:
column.append(place)
counts[(place, animal)] += count
result = [header]
for (place, animal), count in counts.items():
col = header.index(animal)
row = column.index(place)
if row >= len(result):
result.append([place] + [""] * (len(header) - 1))
result[row][col] = count