Skip to content
Advertisement

Extracting sublists of specific elements from Python lists of strings

I have a large list of elements

JavaScript

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

I tried to do:

JavaScript

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

The full solution would be something like:

JavaScript

Now lists will contain all the lists you want.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement