2015-07-19 77 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]