0

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
1
  • sorry for interrupting, I'm new in programming Commented Nov 12, 2019 at 9:57

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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']

Comments

0

Maybe not the fatest solution but it works:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.