在 Python 中,是否有一种优雅的方法可以在没有显式循环的情况下以自定义格式打印列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4440516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:44:45  来源:igfitidea点击:

In Python, is there an elegant way to print a list in a custom format without explicit looping?

pythonlist

提问by stefaanv

I know you can do

我知道你可以

print str(myList)

to get

要得到

[1, 2, 3]

and you can do

你可以做

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

to get

要得到

0: 1  
1: 2  
2: 3    

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

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

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

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

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?

它并没有那么冗长,但至少我在一个(复合)语句中得到了一个自定义字符串。你能做得更好吗?

采纳答案by SilentGhost

>>> 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 isexplicit looping.

注意:您只需要了解列表推导式或迭代生成器表达式显式循环。

回答by Lucas Moeskops

l = [1, 2, 3]
print '\n'.join(['%i: %s' % (n, l[n]) for n in xrange(len(l))])

回答by the wolf

Another:

其他:

>>> lst=[10,11,12]
>>> fmt="%i: %i"
>>> for d in enumerate(lst):
...    print(fmt%d)
... 
0: 10
1: 11
2: 12

Yet another form:

还有一种形式:

>>> for i,j in enumerate(lst): print "%i: %i"%(i,j)

That method is nice since the individual elements in tuples produced by enumeratecan be modified such as:

该方法很好,因为可以修改enumerate生成的元组中的各个元素,例如:

>>> for i,j in enumerate([3,4,5],1): print "%i^%i: %i "%(i,j,i**j)
... 
1^3: 1 
2^4: 16 
3^5: 243 

Of course, don't forget you can get a slice from this like so:

当然,不要忘记你可以像这样得到一个切片:

>>> for i,j in list(enumerate(lst))[1:2]: print "%i: %i"%(i,j)
... 
1: 11

回答by eyquem

from time import clock
from random import sample

n = 500
myList = sample(xrange(10000),n)
#print myList

A,B,C,D = [],[],[],[]

for i in xrange(100):
    t0 = clock()
    ecr =( '\n'.join('{}: {}'.format(*k) for k in enumerate(myList)) )
    A.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join(str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList))
    B.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join(map(lambda x: '%s: %s' % x, enumerate(myList)))
    C.append(clock()-t0)

    t0 = clock()
    ecr = '\n'.join('%s: %s' % x for x in enumerate(myList))
    D.append(clock()-t0)

print '\n'.join(('t1 = '+str(min(A))+'   '+'{:.1%}.'.format(min(A)/min(D)),
                 't2 = '+str(min(B))+'   '+'{:.1%}.'.format(min(B)/min(D)),
                 't3 = '+str(min(C))+'   '+'{:.1%}.'.format(min(C)/min(D)),
                 't4 = '+str(min(D))+'   '+'{:.1%}.'.format(min(D)/min(D))))

For n=500:

对于 n=500:

150.8%.
142.7%.
110.8%.
100.0%.

For n=5000:

对于 n=5000:

153.5%.
176.2%.
109.7%.
100.0%.

Oh, I see now: only the solution 3 with map() fits with the title of the question.

哦,我现在明白了:只有带有 map() 的解决方案 3 符合问题的标题。

回答by Thomas Ahle

>>> from itertools import starmap

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

This uses itertools.starmap, which is like map, except it *s the argument into the function. The function in this case is '{}: {}'.format.

这使用itertools.starmap, 就像map,除了它*是函数的参数。这种情况下的函数是'{}: {}'.format

I would prefer the comprehension of SilentGhost, but starmapis a nice function to know about.

我更喜欢 SilentGhost 的理解,但这starmap是一个很好的功能。

回答by Manuzor

In python 3s print function:

在python 3s打印功能中:

lst = [1, 2, 3]
print('My list:', *lst, sep='\n- ')

Output:

输出:

My list:
- 1
- 2
- 3

Con: The sepmust be a string, so you can't modify it based on which element you're printing. And you need a kind of headerto do this (above it was 'My list:').

Consep必须是字符串,因此您不能根据要打印的元素修改它。并且您需要一种标题来执行此操作(在其上方'My list:')。

Pro: You don't have to join()a list into a string object, which might be advantageous for larger lists. And the whole thing is quite concise and readable.

:你不必join()名单成一个字符串对象,这可能是大名单有利。整个事情非常简洁易读。

回答by John La Rooy

Starting from this:

从此开始:

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

You can get rid of the joinby passing \nas a separator to print

您可以join通过\n作为分隔符传递来摆脱print

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

Now you see you could use map, but you'll need to change the format string (yuck!)

现在您看到您可以使用map,但您需要更改格式字符串(糟糕!)

>>> print(*(map('{0[0]}: {0[1]}'.format, enumerate(lst))), sep="\n")
0: 1
1: 2
2: 3

or pass 2 sequences to map. A separate counter and no longer enumerate lst

或将 2 个序列传递给map. 一个单独的计数器,不再枚举lst

>>> from itertools import count
>>> print(*(map('{}: {}'.format, count(), lst)), sep="\n")
0: 1
1: 2
2: 3

回答by Adam

Take a look on pprint, The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. This may be the case if objects such as files, sockets or classes are included, as well as many other objects which are not representable as Python literals.

看看pprint, pprint 模块提供了一种功能,可以“漂亮地打印”任意 Python 数据结构的形式,可以用作解释器的输入。如果格式化结构包含不是基本 Python 类型的对象,则表示可能无法加载。如果包含文件、套接字或类等对象,以及许多其他不能表示为 Python 文字的对象,则可能会出现这种情况。

>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberHyman', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[   ['spam', 'eggs', 'lumberHyman', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberHyman',
    'knights',
    'ni']
>>> pp = pprint.PrettyPrinter(width=41, compact=True)
>>> pp.pprint(stuff)
[['spam', 'eggs', 'lumberHyman',
  'knights', 'ni'],
 'spam', 'eggs', 'lumberHyman', 'knights',
 'ni']
>>> tup = ('spam', ('eggs', ('lumberHyman', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam', ('eggs', ('lumberHyman', ('knights', ('ni', ('dead', (...)))))))