简体   繁体   English

在python中将字符串转换为有序列表

[英]converting a string into ordered list in python

top_imdb_movies = ['The Shawshank Redemption', 'The Godfather', 'The Dark Knight']

How would i iterate over top_imdb_movies to display the following ordered list:我将如何迭代 top_imdb_movies 以显示以下有序列表:

1.The Shawshank Redemption
2.The Godfather
3.The Dark Knight

Use enumerate with a start value of 1 as follows:使用起始值为 1 的枚举,如下所示:

top_imdb_movies = ['The Shawshank Redemption', 'The Godfather', 'The Dark Knight']

for i, movie in enumerate(top_imdb_movies, 1):
    print(f'{i}. {movie}')

Output:输出:

1. The Shawshank Redemption
2. The Godfather
3. The Dark Knight
top_imdb_movies = ['1. The Shawshank Redemption', '2. The Godfather', '3. The Dark Knight']

for i in top_imbd_movies:
    print(i)

Maybe something like也许像

i=1
for movie in top_imdb_movies:
   print(f"{i}. {movie}"
   i = i+1
top_imdb_movies = ['The Shawshank Redemption', 'The Godfather', 'The Dark Knight']

movie_number=0

for movie_number, movie in enumerate(top_imdb_movies):
    print(f"{movie_number + 1}. {movie}")

output输出

1. The Shawshank Redemption
2. The Godfather
3. The Dark Knight

By composing functions:通过组合函数:

top_imdb_movies = ['The Shawshank Redemption', 'The Godfather', 'The Dark Knight']

print(*map('{}.{}'.format, range(1, 1+len(top_imdb_movies)), top_imdb_movies), sep='\n')

Added the sep='\n' parameter to print and expanding the iterable object with * to avoid the for -loop添加了sep='\n'参数来print和扩展可迭代对象*以避免for -loop


If the list is long you can define a template string as a variable to gather better performance, template = '{}.{}'如果列表很长,您可以将模板字符串定义为变量以获得更好的性能, template = '{}.{}'

template = '{}.{}'
print(*map(template.format, range(1, 1+len(top_imdb_movies)), top_imdb_movies), sep='\n')

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

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