1

I have a csv file that I process this way. The csv containing just numbers is such:

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)

output:

[[1, 5, 6, 8, 45, 56], [2, 6, 34, 42, 56, 98], [1, 5, 6, 8, 45, 56]]

How can I make it print the most frequently occurring lists? For example: 1, 5, 6, 8, 45, 56 2 times in list?

1
  • using the .count() method perhaps? Commented Jun 26, 2021 at 12:44

4 Answers 4

2

You can use the Counter class from collections. It can't take lists of lists directly, but by converting the inner lists to tuples you can count them:

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)

yields the most common list and how many times it occured:

[((1, 5, 6, 8, 45, 56), 2)]

Counter have several other useful functions when it comes to counting, and it is very performant.

The docs for Counter

Sign up to request clarification or add additional context in comments.

Comments

0

Use count row when you are appending numbers

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)

Comments

0
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))]

Output:

[1, 5, 6, 8, 45, 56]

Comments

0

If you don't want to use Counter, you can do the following (l is your list):

d={tuple(i):l.count(i) for i in l}
d=sorted(d, key=lambda x: d[x], reverse=True)

res=list(d[0])

print(res)

#[1, 5, 6, 8, 45, 56]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.