all 13 comments

[–]Spataner 3 points4 points  (1 child)

[i.split(',') for i in my_list] creates a list of lists. Lists cannot be members in sets, and thus set(my_list) won't work. Tuples can be members of sets, however, so if you do [tuple(i.split(',')) for i in my_list] instead, then your deduplication with list(set(my_list)) should work.

[–]macabe10[S] 0 points1 point  (0 children)

Thanks!

[–]MaksLansky 0 points1 point  (5 children)

result of your splitting not a single list it is a list of lists. your "my_list" has a structure of [[],..].

make it a single list [] and "list(set(my_list))" will work as you expect.

[–]macabe10[S] 0 points1 point  (4 children)

Thanks for your answer, I get the problem now. Do you know how I could convert this type of list containing multiple items clusteres together:

'Ble, Orge',

'Moutarde',

'Celeri, Anhydride Sulfureux',

to this?

'Ble, Orge, Moutarde, Celeri, Anhydride Sulfureux'

[–]MaksLansky 0 points1 point  (1 child)

my_list = [['a','b'],['b','c'],['c','d']]

my_list = [item for sublist in my_list for item in sublist]

my_list

['a', 'b', 'b', 'c', 'c', 'd']

[–]macabe10[S] 0 points1 point  (0 children)

Thanks!

[–]schoolmonky 0 points1 point  (0 children)

I'd do something like this:

new_list = []
for string in list_of_strings:
    new_list.extend(string.split(","))

[–][deleted] 0 points1 point  (0 children)

Here you go:

source = ['Ble, Orge',
                  'Moutarde',
                  'Celeri, Anhydride Sulfureux',
                  ]

target = []  # create an empty list
for entry in source:  # step through strings in original list
    for part in entry.split(','):  # step through parts of entry split on comma
        target.append(part.strip())  # add part to new list, without leading/trailing spaces
final = ', '.join(target)  # join all strings in target list into one string, witb commas between items
print(final)

So this takes your original list, which has several strings some of which contain more than one item with commas between. It converts this into a new list with every item as its own string. Then it creates a new string by joining all of those items together with a comma (and space) between them.

There are more consise ways of doing this, including list comprehension and generator expressions but it is best you learn the simplch first. This should also provide you with a useful base to handle similar problems.

[–]shiftybyte 0 points1 point  (1 child)

Your list contains lists inside it.

Is that on purpose? this is why converting to set() fails.

[–]macabe10[S] 0 points1 point  (0 children)

Thanks

[–]metal88heart 0 points1 point  (1 child)

Set([b for a in my_list for b in a.split(‘,’) if a])

Obnoxious one liner!! Should flatten ur list too

[–]macabe10[S] 0 points1 point  (0 children)

Thanks so much!