Home > Net >  How to count the same strings in multiple list in a list
How to count the same strings in multiple list in a list

Time:04-19

I'm a dictionary variable, in which have to count the same strings in multiple list inside a list

example:

df={"123":{"grade":[["DESC",12hwe],["age",28]["DESC",jbwdjb],["score",76]]}

I want to count the number of lists with "DESC" inside the list( for the above example,the count of "DESC" is 2)

for i in range(df["123"]["grade"]):
  print(count(df["123"]["grade"][i][0]=="DESC"))

Any suggestions would be much appriciated !

CodePudding user response:

your example data has a tuple in it , and I assume that if it is regular array so you can count it like that

df = { "123": {"grade": [["DESC", "12hwe"], ["age", 28],["DESC", "jbwdjb"], ["score", 76]]}}
listOfList = df["123"]["grade"]

splash = [i == "DESC" for x in listOfList for i in x]

print(sum(splash))

CodePudding user response:

Maybe not a very efficient solution but still leads to your desired output. I assumed it is just a simple case of counting the occurrence of DESC string:

import pandas as pd
from itertools import chain
import re

df = {"123":{"grade":[["DESC",'12hwe'],["age",28],["DESC",'jbwdjb'],["score",76]]}}

# First we flatten your nested dictionaries
df2 = pd.json_normalize(df)

# Then we create a list out of the resulting data frame
lst = list(chain.from_iterable(df2['123.grade']))

# Now we count the number of occurrence in the resulting list
len(re.findall('DESC', str(lst)))

2

Since I have recently started using Python I would appreciate any hint to improve this solution.

  • Related