how to store all the values of a list of lists and the frequence of their appearance as well as their index?

0

Issue

my code is this

idnt=[] 
idntfrq=[]           

for i in range(len(occ)):
    idnt.append([])
    idntfrq.append([])
    for j in range(len(occ[i])):
        for j2 in range(j,len(occ[i])):
            for d in occ[i][j]:
                idnt[i].append(d)
                idntfrq[i].append([j])
                occ[i][j].remove(d)
                for d2 in occ[i][j2]:
                    if d==d2:
                
                        idntfrq[i][-1].append(j2)
                        occ[i][j2].remove(d)
        

I need the number of appearances of each value as well as their indexes

the list of lists is occ (50 lists inside with various lengths each)

the thought was to iterate over everything,store each value in the idnt[i] list and the
index of the list in which it appears to the idntfrq[i] list and then remove the
element from the list of the current itteration,the occ list should be empty after
that but it is not,i uploaded a prntscr of the occ[0][0] to see what i mean

NOTE: each list inside a list contains every element only once , but i want to count the
occurences across all the lists inside every occ[i] (for i in 50)and also keep the indexenter image description here

Solution

This code will do what you are asking:

mainList = [[1,2,3],[3,4,5],[1,5,9]]
d = {}
for l in mainList:
    for item in l:
        if item in d.keys():
            d[item] +=1
        else:
            d[item] = 1
print(d)

Output:

{1: 2, 2: 1, 3: 2, 4: 1, 5: 2, 9: 1}

It gives the answer in a dictionary where keys are the items and the values is the number of appearances.

This output and be further formatted if needed.

If you need the indexes of each time a number appears you can simply add a dictionary di that has the items as keys and a list of index pairs at which the item appears as the values.

This can be done by adding di[item].append([idx,jdx]) and di[item] = [[idx,jdx]] inside the loop and defining it as di = {} before the loop like this:

mainList = [[1,2,3],[3,4,5],[1,5,9]]
d = {}
di = {}
idx = -1
for l in mainList:
    idx += 1
    jdx = -1
    for item in l:
        jdx += 1
        if item in d.keys():
            d[item] +=1
            di[item].append([idx,jdx])
        else:
            d[item] = 1
            di[item] = [[idx,jdx]]
print(d)
print(di)

Ouput:

{1: 2, 2: 1, 3: 2, 4: 1, 5: 2, 9: 1}
{1: [[0, 0], [2, 0]], 2: [[0, 1]], 3: [[0, 2], [1, 0]], 4: [[1, 1]], 5: [[1, 2], [2, 1]], 9: [[2, 2]]}

Answered By – Eli Harold

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More