我有一个csv文件,我用这种方式处理。只有号码的csv是这样的:
1、5、6、8、45、56
2、6、34、42、56、98
1、5、6、8、45、56
..。
import csv
numbers = []
with open('example.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
numbers.append(row)
print(numbers)产出:
[[1, 5, 6, 8, 45, 56], [2, 6, 34, 42, 56, 98], [1, 5, 6, 8, 45, 56]]如何让它打印最频繁出现的列表?例如: 1,5,6,8,45,56 2次?
发布于 2021-06-26 12:46:29
您可以使用来自collections的collections类。它不能直接获取列表列表,但是通过将内部列表转换为元组,您可以计算它们:
from collections import Counter
lst = [[1, 5, 6, 8, 45, 56], [2, 6, 34, 42, 56, 98], [1, 5, 6, 8, 45, 56]]
Counter(tuple(i) for i in lst).most_common(1)产生最常见的列表以及发生了多少次:
[((1, 5, 6, 8, 45, 56), 2)]当涉及到计数时,计数器还有其他一些有用的功能,而且它的性能非常好。
发布于 2021-06-26 12:49:19
在追加数字时使用计数行
import csv
numbers = []
max_occurance_count=0
with open('example.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
numbers.append(row)
if numbers.count(row) > max_occurance_count:
max_occurance_count=numbers.count(row)
max_occured_row = row
print(numbers)
print (max_occured_row)发布于 2021-06-26 12:50:39
import csv
numbers = []
with open('example.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
numbers.append(row)
a = [] #empty list
for i in numbers:
a.append(numbers.count(i))
numbers[a.index(max(a))]输出:
[1, 5, 6, 8, 45, 56]https://stackoverflow.com/questions/68142453
复制相似问题