3

New to python and can't figure this out:

I am importing data from a cloud data warehouse into Python. This is the resulting data structure:

[('A,B',),
 ('A',),
 ('A,B,C',)]

How can I convert the data into this format:

[['A','B'],
 ['A'],
 ['A','B','C']]
3
  • 2
    [list(x[0].replace(',','')) for x in lst]... although this feels like the kind of conversion that you shouldn't have to do (like there should be a better way to retrieve/parse the data) Commented Aug 16, 2018 at 14:50
  • 2
    [i[0].split(',') for i in L] Commented Aug 16, 2018 at 15:02
  • This looks like you were given a CSV file and parsed it wrong, and now you want to reorganize what you misparsed, instead of just parsing it right in the first place. Please show us the code that you used to get this data structure and we can probably should you how to fix that code instead. Commented Aug 16, 2018 at 15:24

3 Answers 3

2

I suggest you the following way using a list comprehension to iterate over the list and over each tuple:

my_list = [('A,B',), ('A',), ('A,B,C',)]

new_list = [s.split(',') for t in my_list for s in t]

print(new_list) # [['A', 'B'], ['A'], ['A', 'B', 'C']]

If there is always one string as first element of each tuple, then you could also use the following, which is shorter and more readable:

new_list = [t[0].split(',') for t in my_list]

A last possibility reserved to the lovers of unpacking operator:

new_list = [str(*t).split(',') for t in my_list]
Sign up to request clarification or add additional context in comments.

Comments

0

my_list = [('A,B',), ('A',), ('A,B,C',)]

new_list = [list(items) for items in my_list]

output :

[['A', 'B'], ['A'], ['A', 'B', 'C']]

2 Comments

This is incorrect. There is no string splitting, or comma replacement applied.
It does not work: it gives [['A,B'], ['A'], ['A,B,C']]
0

This one liner can solve your problem:

data = [('A,B',), ('A',), ('A,B,C',)]

final_data = [list(list(item)[0].split(',')) for item in data]
print(final_data)

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.