0

my list is like this, in example the string is 'a' and 'b' ; i want to return the index of string 'a' and for 'b' then i want to calculate how many time is 'a' repeated in the list1 :

list1=['a','a','b','a','a','b','a','a','b','a','b','a','a']

i want to return the order of evry 'a' in list1 the result should be like this :

a_position=[1,2,4,5,7,8,10,12,13]

and i want to calculate how many time 'a' is repeated in list1: a_rep=9

2 Answers 2

2

You could do below:

a_positions = [idx + 1 for idx, el in enumerate(list1) if el == 'a']
a_repitition = len(a_positions)

print(a_positions):

[1, 2, 4, 5, 7, 8, 10, 12, 13]

print(a_repitition):

9

If you need repititions of each element you can also use collections.Counter

from collections import Counter
counter = Counter(list1)

print(counter['a']):

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

Comments

1

If you want to get the indices and counts of all letters:

list1=['a','a','b','a','a','b','a','a','b','a','b','a','a']
pos = {}
for i,c in enumerate(list1, start=1): # 1-based indexing
    pos.setdefault(c, []).append(i)
pos
# {'a': [1, 2, 4, 5, 7, 8, 10, 12, 13],
#  'b': [3, 6, 9, 11]}

counts = {k: len(v) for k,v in pos.items()}
# {'a': 9, 'b': 4}

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.