I have a large list of elements
JavaScript
x
11
11
1
a = [['qc1l1.1',
2
'qc1r2.1',
3
'qc1r3.1',
4
'qc2r1.1',
5
'qc2r2.1',
6
'qt1.1',
7
'qc3.1',
8
'qc4.1',
9
'qc5.1',
10
'qc6.1', ..]
11
From this list i want to extract several sublists for elements start with the letters “qfg1” “qdg2” “qf3” “qd1” and so on.
such that:
JavaScript
1
4
1
list1 = ['qfg1.1', 'qfg1.2', .]
2
list2 = ['qfg2.1', 'qfg2.2',,,]
3
4
I tried to do:
JavaScript
1
5
1
list1 = []
2
for i in all_quads_names:
3
if i in ['qfg']:
4
list1.append(i)
5
but it gives an empty lists, how can i do this without the need of doing loops as its a very large list.
Advertisement
Answer
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:
JavaScript
1
5
1
list1 = []
2
for name in all_quads_names:
3
if name.startswith('qc1r'):
4
list1.append(name)
5
The full solution would be something like:
JavaScript
1
9
1
prefixes = ['qfg', 'qc1r']
2
lists = []
3
for pref in prefixes:
4
list = []
5
for name in all_quads_names:
6
if name.startswith(pref):
7
list.append(name)
8
lists.append(list)
9
Now lists will contain all the lists you want.