简体   繁体   English

如何摆脱以下枚举 python 程序作为列表

[英]How to get out of the following enumerate python program as a List

for i,x in enumerate(['A','B','C']):
    print(i, x)

Current output is:当前 output 为:

0 A
1 B
2 C

I need the output to be as [(0,A), (1,B), (2,C)]我需要 output 为[(0,A), (1,B), (2,C)]

Just convert the enumerate iterator to a list:只需将enumerate迭代器转换为列表:

out = list(enumerate(['A','B','C']))

Output: [(0,A), (1,B), (2,C)] (the output is a list object) Output: [(0,A), (1,B), (2,C)] (output 是一个列表对象)

If you just want to print:如果您只想打印:

print(list(enumerate(['A','B','C'])))

Finally, if you're looking to build a string with your specific format, use:最后,如果您要构建具有特定格式的字符串,请使用:

print('[%s]' % ','.join(f'({i},{v})' for i,v in enumerate(['A','B','C'])))

Output: '[(0,A),(1,B),(2,C)]' Output: '[(0,A),(1,B),(2,C)]'

Wrap your call to enumerate in a call to list :将您的调用包装在对enumerate的调用list

out = list(enumerate(['A', 'B', 'C']))

Output: Output:

>>> out
[(0, 'A'), (1, 'B'), (2, 'C')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM