0

I am working on a project where i want to use list comprehension for printing out a nested list like below

[['Jonathan', 'Adele', 'David', 'Fletcher', 'Steven',["A","B","C"]],['Nathan', 'Tom', 'Tim', 'Robin', 'Lindsey']]

This need to print every name as string. I am able to print it like below

['Jonathan',
 'Adele',
 'David',
 'Fletcher',
 'Steven',
 ['A', 'B', 'C'],
 'Nathan',
 'Tom',
 'Tim',
 'Robin',
 'Lindsey']

However, i don't want A,B,C to be printed as a list. I need them in print like other names. How can i apply list comprehension here? Please help.

Avij
  • 684
  • 7
  • 17
  • Possible duplicate of [Flatten (an irregular) list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists) – Miraj50 Nov 01 '17 at 13:50
  • No, i am looking out if list comprehension is possible, i could easily write out a loop like that, but its not what i am looking out – Avij Nov 01 '17 at 13:57
  • @Avij how do you able to print the 1st nest? There are 2 nests right..? –  Nov 01 '17 at 14:55
  • 1
    [name for names in myname_list for name in names] – Avij Nov 01 '17 at 15:24

2 Answers2

0

I may contribute with a different list. These process

A=[['aaa', 'bbb', 'ccc',["A","B","C"]],['ddd', 'eee', 'fff']];

B=A[0];

B.extend(A[1]);

will result in for B :

['aaa', 'bbb', 'ccc',["A","B","C"],'ddd', 'eee', 'fff'];

After this you may do similar steps :

C = B.pop(3);

B.extend(C);

Now the list B has become :

['aaa', 'bbb', 'ccc','ddd', 'eee', 'fff', "A", "B", "C"];

This may not be exactly as same as what you are looking for. Hope this helps.

0

You're probably better off using a recursive function instead of list comprehension, as this will work for general cases with more nestings.

my_list = [["Jonathan", "Adele", "David", "Fletcher", "Steven", ["A", "B", "C"]], ["Nathan", "Tom", "Tim", "Robin", "Lindsey"]]

def flatten(list_):

    result = []

    for element in list_:

        if type(element) == list:

            result += flatten(element)

        else:

            result.append(element)

    return result

print("Before:\t{}".format(my_list))

my_list = flatten(my_list)

print("After:\t{}".format(my_list))

Output:

Before: [['Jonathan', 'Adele', 'David', 'Fletcher', 'Steven', ['A', 'B', 'C']], ['Nathan', 'Tom', 'Tim', 'Robin', 'Lindsey']]
After:  ['Jonathan', 'Adele', 'David', 'Fletcher', 'Steven', 'A', 'B', 'C', 'Nathan', 'Tom', 'Tim', 'Robin', 'Lindsey']
Erick Shepherd
  • 1,403
  • 10
  • 19