Brendan Brendan - 4 months ago 7
Python Question

Python List of Strings to Tuple Pairs

I am having some difficulty coming up with an efficient way of taking a list of strings and converting it to tuple pairs. I have a list similar to:

listOfNames = ['red-l','blue-l','green-s','red-s','blue-s']


Every color in this example (red, blue, and green) has either a '-l' or '-s' entry or both. I need to convert this list of strings into tuple pairs such as:

tupleOfNames = [('red-l','red-s'),(None,'green-s'),('blue-l','blue-s')]


I think regular expressions is needed but I am not sure how to do so. Any help is greatly appreciated. Thanks

Answer

A possible solution, We can sort the list firstly and then groupby the color part of each term and transform each group into a tuple, if it contains only one element insert a None in the tuple:

import re
from itertools import groupby

li = []
listOfNames.sort()
for k, g in groupby(listOfNames, lambda s: re.findall("(.*)-", s)):
    liG = list(g)
    if len(liG) == 1:
        li.append((None, liG[0]))
    else:
        li.append(tuple(liG))

li
# [('blue-l', 'blue-s'), (None, 'green-s'), ('red-l', 'red-s')]