top_imdb_movies = ['The Shawshank Redemption', 'The Godfather', 'The Dark Knight']
我將如何迭代 top_imdb_movies 以顯示以下有序串列:
1.The Shawshank Redemption
2.The Godfather
3.The Dark Knight
uj5u.com熱心網友回復:
也許像
i=1
for movie in top_imdb_movies:
print(f"{i}. {movie}"
i = i 1
uj5u.com熱心網友回復:
top_imdb_movies = ['1. The Shawshank Redemption', '2. The Godfather', '3. The Dark Knight']
for i in top_imbd_movies:
print(i)
uj5u.com熱心網友回復:
使用起始值為 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}')
輸出:
1. The Shawshank Redemption
2. The Godfather
3. The Dark Knight
uj5u.com熱心網友回復:
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}")
輸出
1. The Shawshank Redemption
2. The Godfather
3. The Dark Knight
uj5u.com熱心網友回復:
通過組合函式:
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')
添加sep='\n'引數print并擴展可迭代物件*以避免for-loop
如果串列很長,您可以將模板字串定義為變數以獲得更好的性能,template = '{}.{}'
template = '{}.{}'
print(*map(template.format, range(1, 1 len(top_imdb_movies)), top_imdb_movies), sep='\n')
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495151.html
上一篇:給定一個包含n個元素的陣列a,列印至少出現3次的任何值,如果沒有這樣的值,則列印-1
下一篇:For回圈只回傳最后一個數字
