ely66
ely66

Reputation: 185

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.

Upvotes: 1

Views: 68

Answers (4)

L4ur3nt
L4ur3nt

Reputation: 118

Try to revert you if statement and to compare a string to the list elements :

if "qfg" in i:

you can refer to this question : Searching a sequence of characters from a string in python

you have many python methods to do just that described here: https://stackabuse.com/python-check-if-string-contains-substring/

Edit after AminM coment :

From your exemple it doesn't seem necessary to use the startwith() method, but if your sublist ("qfg") can also be found later in the string and you need to find only the string that is starting with "qfg", then you should have something like :

if i.startswith("qfg"):

Upvotes: 1

AminM
AminM

Reputation: 856

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.

Upvotes: 1

fish2000
fish2000

Reputation: 4435

Try something like this:


prefixes = ['qfg1', … ]
top = [ […], […], … ]
extracted = []

for sublist in top:
    if sublist and any(prefix in sublist[0] for prefix in prefixes):
        extracted.append(sublist)

Upvotes: 0

codewhat
codewhat

Reputation: 11

You are looking for 'qfg' in the ith element of the all_quads_names. So, try the following:

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

Upvotes: 1

Related Questions