jeudi 15 juillet 2021

Joining strings with a list of lists if they meet a specific condition

I have this list of lists:

x = [["hello", 1, "pacific", 'M','F','W'], ["yes", 4, 5, "turn", 'S', 'F', 'Su']]

I would like to join specific items in the list: 'M','F','W','S','Su'

So if any of these items exist in the list they should be joined together resulting in:

x = [["hello", 1, "pacific", 'M,F,W'], ["yes", 4, 5, "turn", 'S,F,Su']]

My Current attempt looks like this:

x = [["hello", 1, "pacific", 'M','F','W'], ["yes", 4, 5, "turn", 'S', 'F', 'Su']]

z = []

for item in x: 

    for y in item:

        if y == 'M' or y == 'F' or y =='W' or y == 'S' or y =='Su':

            item.index(y)

            z.append((item.index(y)))

        else:
            pass

x[min(z):max(z)+1] = [','.join(item[min(z):max(z)+1])]

print(x)

I thought I could grab the positions of the specific strings I want in the list and then join them using min and max.

My code returns:

[['hello', 1, 'pacific', 'M', 'F', 'W'], ['yes', 4, 5, 'turn', 'S', 'F', 'Su'], 'turn,S,F']

Any help is very much appreciated!

Aucun commentaire:

Enregistrer un commentaire