Tony Smears
Tony Smears

Reputation: 13

Python position of a character in a string in a list

So, say I have a list with 5 strings. The strings are seven characters long.

list = ["000000A", "000001A", "000002B", "000003C", "000004C"]

Now, with this list, I want to find what position the string is in the list which the 7th character is equal to A. Then I want to find what position the string is in the list which the 7th character is equal to B. Then finally the same for C.

I was thinking along the lines of:

letters = ["A","B","C"]
for i in range(len(letters)):
   for j in range(len(list)):
           for k, l in enumerate(list[j][6]):
               if l == (letters[i]):
                   print(k)

Could anyone point me in the right direction or explain why this would work?

Upvotes: 1

Views: 97

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

lst = ["000000A", "000001A", "000002B", "000003C", "000004C"]
a = ([i for i,s in enumerate(lst) if s[6] == "A"])

So to get all three:

a = []
b = []
c= []
for i, s in enumerate(lst):
    if s[6] == "A":
        a.append(i)
    elif s[6] == "B":
        b.append(i)
    elif s[6] == "C":
        c.append(i)

Or you can store all in a defaultdict using s[6] as the key:

from collections import defaultdict

inds = defaultdict(list)
for i, s in enumerate(lst):
    inds[s[6]].append(i)

print(inds)
defaultdict(<type 'list'>, {'A': [0, 1], 'C': [3, 4], 'B': [2]})

Upvotes: 1

Related Questions