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?
它不是那么冗长,但至少我在一个(复合)语句中得到一个自定义字符串。你能做得更好吗?
7 个解决方案
#1
85
>>> 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.
注意:您只需要了解列表理解或迭代生成器表达式是显式循环。
#2
8
l = [1, 2, 3]
print '\n'.join(['%i: %s' % (n, l[n]) for n in xrange(len(l))])
#3
4
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 sep
must be a string, so you can't modify it based on which element you're printing. And you need a kind of header to do this (above it was 'My list:'
).
Con:sep必须是一个字符串,因此您无法根据要打印的元素对其进行修改。你需要一种标题才能做到这一点(上面是'我的清单:')。
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.
Pro:您不必将列表加入()到字符串对象中,这对于较大的列表可能是有利的。整个过程非常简洁易读。
#4
4
>>> 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 starmap
is a nice function to know about.
我更喜欢理解SilentGhost,但是starmap是一个很好的功能。
#5
3
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 enumerate can be modified such as:
该方法很好,因为枚举产生的元组中的各个元素可以修改,例如:
>>> 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
#6
3
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符合问题的标题。
#7
3
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 join
by passing \n
as a separator to print
您可以通过传递\ n作为分隔符来删除连接
>>> 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个序列进行映射。一个单独的计数器,不再列举lst
>>> from itertools import count
>>> print(*(map('{}: {}'.format, count(), lst)), sep="\n")
0: 1
1: 2
2: 3
#1
85
>>> 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.
注意:您只需要了解列表理解或迭代生成器表达式是显式循环。
#2
8
l = [1, 2, 3]
print '\n'.join(['%i: %s' % (n, l[n]) for n in xrange(len(l))])
#3
4
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 sep
must be a string, so you can't modify it based on which element you're printing. And you need a kind of header to do this (above it was 'My list:'
).
Con:sep必须是一个字符串,因此您无法根据要打印的元素对其进行修改。你需要一种标题才能做到这一点(上面是'我的清单:')。
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.
Pro:您不必将列表加入()到字符串对象中,这对于较大的列表可能是有利的。整个过程非常简洁易读。
#4
4
>>> 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 starmap
is a nice function to know about.
我更喜欢理解SilentGhost,但是starmap是一个很好的功能。
#5
3
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 enumerate can be modified such as:
该方法很好,因为枚举产生的元组中的各个元素可以修改,例如:
>>> 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
#6
3
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符合问题的标题。
#7
3
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 join
by passing \n
as a separator to print
您可以通过传递\ n作为分隔符来删除连接
>>> 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个序列进行映射。一个单独的计数器,不再列举lst
>>> from itertools import count
>>> print(*(map('{}: {}'.format, count(), lst)), sep="\n")
0: 1
1: 2
2: 3