【问题标题】:How to iterate over dictionary items and indexes starting from 1?如何从 1 开始迭代字典项和索引?
【发布时间】:2020-08-09 22:59:01
【问题描述】:

我想这样:(排序数字“1-3”而不是“0-2”)

  1. 叫约翰
  2. 20 岁
  3. 性别男

【问题讨论】:

  • 嗨,请给我们发送我 sn-p 代码的代码。快速回答
  • 请将代码和数据添加为文本 (using code formatting),而不是图像。图片:A)不允许我们复制粘贴代码/错误/数据进行测试; B) 不允许根据代码/错误/数据内容进行搜索;和many more reasons。除了代码格式的文本之外,只有在图像添加了一些重要的东西,而不仅仅是文本代码/错误/数据传达的内容时,才应该使用图像。见minimal reproducible example

标签: python python-3.x list dictionary iteration


【解决方案1】:

您可以使用 enumerate 及其 start 参数,它就是为此而生的:

for i, (key, value) in enumerate(my_lib.items(), start=1):
    print(i, key, value)

【讨论】:

    【解决方案2】:

    试试这个:

    for i, (x, y) in enumerate(my_lib.items()):
        print(i+1, x, y)
    

    【讨论】:

      猜你喜欢
      • 2014-03-04
      • 1970-01-01
      • 2014-01-15
      • 2021-03-31
      • 2019-05-25
      • 2013-07-21
      • 2020-11-14
      • 2013-01-01
      • 1970-01-01
      相关资源
      最近更新 更多