Home > Mobile >  How to count specific characters in a list for each string separately
How to count specific characters in a list for each string separately

Time:12-08

as i title says. I think code will describe what i want to do.

input:

words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy']

expected output:

sum of polish signs in words - [0, 0, 3, 2, 3, 0, 1, 0]

My work:

words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy']
sumOfChars = [len(i) for i in words]
polish = 'ą ć ę ł ń ó ś ź ż'.split()
lista = []
for i in words:
    for x in i:
        if x in polish:
            lista.append(x)
print(sumOfChars)
print(lista)

And my output:

[3, 12, 4, 4, 16, 8, 7, 15]
# ^ sum of chars in every string
['ż', 'ó', 'ł', 'ź', 'ń', 'ż', 'ó', 'ł', 'ę']
# ^ special signs in my strings

CodePudding user response:

You could create a list for each word and count the length of each sublist. I've updated your code accordingly:

words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy']
sumOfChars = [len(i) for i in words]
polish = 'ą ć ę ł ń ó ś ź ż'.split()
lista = []
for i in words:
    tmp = []
    for x in i:
        if x in polish:
            tmp.append(x)
    lista.append(tmp)
print(sumOfChars)
print(lista)
print([len(l) for l in lista])

CodePudding user response:

You can do a simple list comprehension:

words = ['oko', 'grzybobranie', 'żółw', 'jaźń', 'zażółcone krzewy', 'hipodrom', 'szczęki', 'kurs poprawkowy']
polish = 'ąćęłńóśźż'

output = [sum(j in polish for j in i) for i in words]

Output:

[0, 0, 3, 2, 3, 0, 1, 0]
  • Related