1

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.

fish2000
  • 4,289
  • 2
  • 37
  • 76
ely66
  • 175
  • 1
  • 11

4 Answers4

1

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"):
L4ur3nt
  • 98
  • 6
  • in is incorrect, because that will merely check if qfg appears in the string. So if the string starts 'aaaqftg1.2' it will still match. You should use startswith() as I suggested below. – AminM Sep 15 '22 at 20:18
  • Fair point, I will add this to my answer, but from the exemple given this is unnecessary – L4ur3nt Sep 15 '22 at 20:24
  • Its never good to make assumptions about the data. The spec says it must "start with" we shouldn't assume that the prefixes don't occur later in the string. – AminM Sep 15 '22 at 20:28
  • But you assume it can occur later in the string, we assume about the data all the time :) – L4ur3nt Sep 15 '22 at 20:32
1

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)
codewhat
  • 11
  • 1
1

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.

AminM
  • 822
  • 4
  • 11
0

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)

fish2000
  • 4,289
  • 2
  • 37
  • 76