crytime
crytime

Reputation: 25

Creating a list of string from a string in a list Python

I'm trying to create a string on a list from a string

It looks like

#My list
list_ = ['a, b, c, d', 'f, g, h, i', 'j, k, l, m', 'n, o, p, q']

#Output that I'm looking for
['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q']

I got it from my code

for row in reader:
    key = row[0]
    pairs_dict[key] = row[1:]
    getlist = pairs_list.append(f"{key}, {', '.join(pairs_dict[key])}")
#pairs_dict is dictionary and pairs_list is empty list

Upvotes: 0

Views: 70

Answers (3)

han solo
han solo

Reputation: 6590

You could just use use str.join on the list and do a list comprehension or use re.split after the joining the list like,

>>> list_
['a, b, c, d', 'f, g, h, i', 'j, k, l, m', 'n, o, p, q']
>>> [x.strip() for x in ','.join(list_).split(',')]
['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q']

Or

>>> import re
>>> list_
['a, b, c, d', 'f, g, h, i', 'j, k, l, m', 'n, o, p, q']
>>> re.split(r',\s*', ','.join(list_)) # split on ',' followed by 0 or more space
['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q']

Upvotes: 2

kuro
kuro

Reputation: 3226

Try to do it using split() like this -

list_ = ['a, b, c, d', 'f, g, h, i', 'j, k, l, m', 'n, o, p, q']
result = []
for r in list_:
   result.extend(r.split(', '))

print(result)

Upvotes: 3

Yohann L.
Yohann L.

Reputation: 1451

Maybe not the fatest solution but it works:

list_ = list(''.join(list_).replace(', ', ''))

Upvotes: 0

Related Questions