2015-07-19 213 views
2
stack = list() 
stack = [[u'hello','world'],[u'blue','sky']] 

如何打印“世界你好”分别在蟒蛇蓝天”分开?打印嵌套列表

+0

https://docs.python.org/2/tutorial /introduction.html#lists – Rishav

回答

1

试试这个方法:

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

更多: 这样看待这段代码,我打印某个对象(OK,它是一个unicode对象)和3个部分,第一部分是来自列表对象的对象,列表对象来自栈(这是也是一个列表对象)。 这是这样的: list(stack) - > list(stack [0]) - > unicode(u'hello') 第二部分是一个字符串对象:''(空格) 第三部分就像第一部分, 列表(堆栈) - >列表(堆栈[0]) - > str('world') 把这3个部分放在一起就是你看到的结果。

我建议你仔细想想你正在使用的东西的类型是什么。因为对于Python中的所有东西,如果你知道它的类型,你很可能会知道你可以使用哪些内置的函数/方法/操作符。这可能太棒了!

还有一件事,我打印一个unicode对象连同2个str对象。

+0

它的工作原理。我可以知道它是如何工作的吗? – jOSe

+0

感谢您的解释 – jOSe

1

想法是在打印之前将每个列表转换为str.join()之间的字符串。

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

使用循环:

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

如果要修改名单:

>>> 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 
+0

@jOSe我会在一段时间内编辑我的答案。 – raymelfrancisco

+0

@raymelfransisco :) – jOSe

1
print "\n".join(map(lambda l: " ".join(map(str, l)), stack)) 
1

使用pprint,这将适用于任何大小和嵌套的数组。

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

具体使用

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

我也想我的答案要与共享的循环,如果条件

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