简体   繁体   English

在python中使用嵌套列表进行列表理解

[英]List comprehensions with nested lists in python

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. 但是,我不希望将A,B,C打印为列表。 I need them in print like other names. 我需要像其他名字一样印刷它们。 How can i apply list comprehension here? 如何在这里应用列表理解? Please help. 请帮忙。

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 : 将导致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 : 现在列表B变为:

['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. 希望这可以帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM