Count First number of all lists in list

Question:

I have a txt file and data in it like this:

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

I want to count all lists 1 numbers and write, after this count all second numbers.
Result should be like this.

  1. Column

1 Result : 1

2 Result : 1

3 Result : 1


  1. Column

1 Result : 1

2 Result : 2

3 Result : 0

I can’t do it, i try many loops, may you help me pls

My code is like this

from ast import literal_eval
count = 0
first = 0
second = 0
third = 0
with open("data.txt") as f:
    matrix = []
    for line in f:
        row = literal_eval(line)
        matrix.append(row)

print(matrix)
print(len(matrix))
print("-----------")
for i in matrix:
    for j in range(3):

        if i[j] == 1:
            first += 1
        elif i[j] == 2:
            second += 1
        elif i[j] == 3:
            third += 1

    print(f"1. Result {first}")
    print(f"2. Result {second}")
    print(f"3. Result {third}")
    print(f"----")
Asked By: onurhanozer

||

Answers:

Use zip to convert the columns to rows so you can use count on them

matrix = [[1, 2, 1],
          [2, 1, 3],
          [3, 2, 3]]

for t in zip(*matrix):
    print(f"1. Result {t.count(1)}")
    print(f"2. Result {t.count(2)}")
    print(f"3. Result {t.count(3)}")
    print(f"----")

Output

1. Result 1
2. Result 1
3. Result 1
----
1. Result 1
2. Result 2
3. Result 0
----
1. Result 1
2. Result 0
3. Result 2

Answered By: Guy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.