用python打印嵌套列表
如何在python中分别打印“hello world”和“blue sky”?在打印之前,通过用python打印嵌套列表,python,list,Python,List,如何在python中分别打印“hello world”和“blue sky”?在打印之前,通过str.join()将每个列表转换为字符串 stack = list() stack = [[u'hello','world'],[u'blue','sky']] 使用循环: >>> stack = [[u'hello', 'world'], [u'blue','sky']] >>> print '\n'.join( ' '.join(s) for s in sta
str.join()
将每个列表转换为字符串
stack = list()
stack = [[u'hello','world'],[u'blue','sky']]
使用循环:
>>> 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
试着这样做:
print "\n".join(map(lambda l: " ".join(map(str, l)), stack))
更多:
考虑这段代码,这样我打印了一个对象(OK,它是一个Unicode对象),结合了3个部分,第一部分是来自一个列表对象的对象,列表对象来自堆栈(这也是一个列表对象)。
是这样的:
列表(堆栈)->列表(堆栈[0])->unicode(u'hello')
第二部分是字符串对象:“”(空格)
第三部分和第一部分一样,
列表(堆栈)->列表(堆栈[0])->str('world')
把这三个部分放在一起就是你看到的结果
我建议你仔细想想你正在使用的东西到底是什么类型的。因为对于python中的所有东西,如果您知道它的类型,您很可能知道可以使用哪些内置函数/方法/运算符。这可能非常棒
还有一件事,我将一个unicode对象和两个str对象一起打印。使用,这将适用于任何大小和嵌套的数组
print stack[0][0]+' '+stack[0][1]
具体使用这个
>>> import pprint
>>> stack = list()
>>> stack = [[u'hello','world'],[u'blue','sky']]
>>> pprint.pprint(stack)
[[u'hello', 'world'], [u'blue', 'sky']]
>>>
我也希望我的答案能与for循环和if条件共享
for s in stack:
print ' '.join(s)
另一个带有f字符串的选项:
if len(stackf) > 0:
for i in range(len(stackf)):
print stackf[i][0]
print stackf[i][1]
输出:
stack = [[u'hello','world'],[u'blue','sky']]
print('\n'.join([f"{d} {e}" for (d,e) in stack]))
stack = [[u'hello','world'],[u'blue','sky']]
print('\n'.join([f"{d} {e}" for (d,e) in stack]))
hello world
blue sky