Search code examples
pythonlistsubstring

Extracting sublists of specific elements from Python lists of strings


I have a large list of elements

a = [['qc1l1.1',
 'qc1r2.1',
 'qc1r3.1',
 'qc2r1.1',
 'qc2r2.1',
 'qt1.1',
 'qc3.1',
 'qc4.1',
 'qc5.1',
 'qc6.1',.................]

From this list i want to extract several sublists for elements start with the letters "qfg1" "qdg2" "qf3" "qd1" and so on.

such that:

list1 = ['qfg1.1', 'qfg1.2',....] 
list2 = ['qfg2.1', 'qfg2.2',,,]
 

I tried to do:

list1 = []
for i in all_quads_names:
    if i in ['qfg']:
       list1.append(i)

but it gives an empty lists, how can i do this without the need of doing loops as its a very large list.


Solution

  • Using in (as others have suggested) is incorrect. Because you want to check it as a prefix not merely whether it is contained.

    What you want to do is use startswith() for example this:

    list1 = []
    for name in all_quads_names:
        if name.startswith('qc1r'):
           list1.append(name)
    

    The full solution would be something like:

    prefixes = ['qfg', 'qc1r']
    lists = []
    for pref in prefixes: 
       list = []
       for name in all_quads_names:
           if name.startswith(pref):
              list.append(name)
       lists.append(list)
    

    Now lists will contain all the lists you want.