You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中遍历字符串列表生成带连续序号有序列表的方法

解决方案

直接用Python内置的enumerate()函数实现最简洁,它能在遍历列表时同时拿到序号和元素值,设置start=1就能让序号从1开始,不用手动给索引加1。

代码如下:

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

for index, name in enumerate(top_imdb_movies, start=1):
    print(f"{index}.{name}")

运行后输出完全符合要求:

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

如果是Python3.6以下版本不支持f-string,把打印语句换成print("{}.{}".format(index, name))效果一样。
不推荐手动维护计数变量的写法,冗余且容易漏改计数导致序号错误,示例如下供参考:

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

内容的提问来源于stack exchange,提问作者amna ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 00:12:17