Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count First number of all lists in list

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"----")

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading