Home > Back-end >  Obtain lists of strings out of items in a sub list
Obtain lists of strings out of items in a sub list

Time:04-20

I have the following list:

data = [['Edith Mcbride', '$1', '21', 'white', '09/15/17'], ['Herbert Tran', '$7', '29', 'white&blue', '09/15/17'], ['Paul Clarke', '$12', '52', 'white&blue', '09/15/17']]

And I'm aiming to clean the strings into separate lists using the following code:

for c in data:
  for n in c:
    customers.append(c[:1])
    sales.append(c[1:2])
    thread_sold.append(c[3:4])

Which outputs each item as a split of the list, i.e:

customers = [['Edith Mcbride'], ['Herbert Tran'], ['Paul Clarke']]
sales = [['$1'], ['$7'], ['$12']]

Which means, in order to transform the strings I need to pass this output through yet another loop in order to obtain the strings outside of its splits, i.e. for customers:

sub_customers= []
for c in customers
  for n in s:
    sub_customers.append(n)

output:

sub_customers = ['Edith Mcbride', 'Herbert Tran', 'Paul Clarke']

Is there a way to make this (obtain lists of strings of every item in the sub list) using a single loop?

CodePudding user response:

sub_customer = [item[0] for item in data]

CodePudding user response:

Instead of appending slices, append as index

for c in data:
  for n in c:
    customers.append(c[0])
    sales.append(c[1])
    thread_sold.append(c[2])

If you slice it returns another list, so as it seems you need just one item so you should index.

CodePudding user response:

You are appending a list to a list (slicing instead of indexing) & also making unnecessary iterations.

This can be done in a single for loop like below

for c in data:
    customers.append(c[1])
    sales.append(c[2])

CodePudding user response:

Assuming... you have a list of lists and the sub-lists are all of the same length you could do it like this:

data = [['Edith Mcbride', '$1', '21', 'white', '09/15/17'], ['Herbert Tran', '$7', '29', 'white&blue', '09/15/17'], ['Paul Clarke', '$12', '52', 'white&blue', '09/15/17']]

tol = [[e[i] for e in data] for i in range(len(data[0]))]

print('\n'.join(str(list_) for list_ in tol))

Now tol is another list of lists giving this output:

['Edith Mcbride', 'Herbert Tran', 'Paul Clarke']
['$1', '$7', '$12']
['21', '29', '52']
['white', 'white&blue', 'white&blue']
['09/15/17', '09/15/17', '09/15/17']
  • Related