简体   繁体   English

在python中打印嵌套列表

[英]Print nested list in python

stack = list()
stack = [[u'hello','world'],[u'blue','sky']]

How to print ' hello world ' separately and ' blue sky ' separately in python ?如何在python中分别打印' hello world '和' blue sky '?

Use pprint , this will work for any size and nesting of array.使用pprint ,这适用于任何大小和嵌套的数组。

>>> import pprint
>>> stack = list()
>>> stack = [[u'hello','world'],[u'blue','sky']]
>>> pprint.pprint(stack)
[[u'hello', 'world'], [u'blue', 'sky']]
>>>

Specifically use this具体用这个

for s in stack:
    print ' '.join(s)

The idea is to convert each list to string by str.join() before printing.这个想法是在打印之前通过str.join()将每个列表转换为字符串。

>>> stack = [[u'hello', 'world'], [u'blue','sky']]
>>> print '\n'.join( ' '.join(s) for s in stack )
hello world
blue sky

Using loops:使用循环:

>>> stack = [[u'hello', 'world'], [u'blue','sky']]
>>> for s in stack:
...    print ' '.join(s)
...
hello world
blue sky

If you want to modify the list:如果要修改列表:

>>> stack = [[u'hello', 'world'], [u'blue','sky']]
>>> stack = [ ' '.join(s) for s in stack ]
>>> print '\n'.join( s for s in stack )
hello world
blue sky
print "\n".join(map(lambda l: " ".join(map(str, l)), stack))

Try this way:试试这个方法:

    print stack[0][0]+' '+stack[0][1]

More: Consider this piece of code this way, I print certain object (OK, it's an unicode object)combined with 3 parts, the first part is the object from a list object,and the list object comes from stack (which is also a list object).更多:以这种方式考虑这段代码,我打印了某个对象(好吧,它是一个 unicode 对象)由 3 部分组合而成,第一部分是来自列表对象的对象,列表对象来自堆栈(这也是一个列表对象)。 It's like this: list(stack)->list(stack[0])->unicode(u'hello') The second part is a string object: ' '(a space) The third part is just like the first part, list(stack)->list(stack[0])->str('world') Put these 3 parts together comes the result you have seen.是这样的: list(stack)->list(stack[0])->unicode(u'hello') 第二部分是一个字符串对象: ' '(a space) 第三部分就像第一部分一样, list(stack)->list(stack[0])->str('world') 把这三部分放在一起就是你看到的结果。

I suggest you think about exactly what the types of the THINGS you are using are.我建议你仔细想想你正在使用的东西的类型是什么。 Because for everything in python, if you know the type of it, you most likely will know what built-in functions/methods/operators you can use.This could be great!因为对于python中的所有东西,如果你知道它的类型,你很可能会知道你可以使用哪些内置函数/方法/运算符。这可能很棒!

And one more thing, I print a unicode object together with 2 str objects.还有一件事,我将一个 unicode 对象与 2 个 str 对象一起打印。

I too wanted my answer to be shared with for loop and if condition我也希望我的答案与 for 循环和 if 条件共享

if len(stackf) > 0:
        for i in range(len(stackf)):
            print stackf[i][0]
            print stackf[i][1]

Another option with f-strings: f 字符串的另一个选项:

stack = [[u'hello','world'],[u'blue','sky']]
print('\n'.join([f"{d} {e}" for (d,e) in stack]))

Output:输出:

hello world
blue sky

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

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