[英]Count First number of all lists in list
我有一个 txt 文件和其中的数据,如下所示:
[1, 2, 1]
[2, 1, 3]
[3, 2, 3]
我想计算所有列表 1 的数字并写,在此之后计算所有第二个数字。 结果应该是这样的。
1 结果:1
2 结果:1
3 结果:1
1 结果:1
2 结果:2
3 结果:0
我做不到,我尝试了很多循环,请你帮帮我
我的代码是这样的
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"----")
使用zip
将列转换为行,以便您可以对它们使用count
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.