Skip to content
Advertisement

List comprehension with pattern match in Python

I have one list named columns, and I have to create one nested list based on a split of the elements (the first three).

For example, I will divide this element ‘101 Drive 1 A’ in ‘101 Drive 1’ and make a group.

JavaScript

The output will look like this:

JavaScript

Advertisement

Answer

One approach using collections.defaultdict:

JavaScript

Output

JavaScript

A more robust alternative, that is going to work for any number at the beginning of the string, is to use a regular expression:

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