简体   繁体   中英

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?

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]})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM