Home > Software engineering >  How to convert a list of tuples to a matrix?
How to convert a list of tuples to a matrix?

Time:02-28

I have the following list of tuples:

list = [(House, Dog, 7), (House, Cat, 5), (Garden, Dog, 4), (Garden, Cat, 3), (Park,Mouse,2)]

I am looking for a matrix with the following structure:

result = [
          ['' ,  Dog,  Cat, Mouse],
          [House,  7,    5,    ''],
          [Garden, 4,    3,    ''],
          [Park,  '',   '',    2 ]
         ]  

CodePudding user response:

This will maintain the order of column/row names and produce the requested solution:

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)

CodePudding user response:

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
  • Related