在Python中,有没有一种优雅的方法可以以自定义格式打印列表而无需显式循环? [英] In Python, is there an elegant way to print a list in a custom format without explicit looping?

查看:116
本文介绍了在Python中,有没有一种优雅的方法可以以自定义格式打印列表而无需显式循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以做到

print str(myList)

获得

[1, 2, 3]

就可以了

i = 0
for entry in myList:
  print str(i) + ":", entry
  i += 1

获得

0: 1  
1: 2  
2: 3    

但是有没有一种方法类似于第一种方法来获得与最后一种相似的结果?

But is there a way similar to the first to get a result similar to the last?

由于我对Python的了解有限(以及文档中的一些帮助),所以我最好的是:

With my limited knowledge of Python (and some help from the documentation), my best is:

print '\n'.join([str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList)])

它的冗长程度并没有那么多,但是至少我在一个(复合)语句中得到了一个自定义字符串. 你可以做得更好吗?

It's not much less verbose, but at least I get a custom string in one (compound) statement. Can you do better?

推荐答案

>>> lst = [1, 2, 3]
>>> print('\n'.join('{}: {}'.format(*k) for k in enumerate(lst)))
0: 1
1: 2
2: 3

注意:您只需要了解列表理解或遍历生成器表达式 是显式循环.

Note: you just need to understand that list comprehension or iterating over a generator expression is explicit looping.

这篇关于在Python中,有没有一种优雅的方法可以以自定义格式打印列表而无需显式循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆