【问题标题】:How to make the output of a list index start with 1?如何使列表索引的输出以 1 开头?
【发布时间】:2020-11-06 03:48:08
【问题描述】:

我有 2 个列表。第一个是: city_indices = list(range(0 , len(cities))) # 列表中有 12 个城市

它的输出是:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

第二个列表是城市名称:

city_names = ['Buenos Aires',
 'Toronto',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Pyeongchang',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls'
]

我必须将两个列表组合的结果放在一个变量中,names_and_ranks = []

我必须合并列表的代码是:

for index in list(range(0,len(cities))):
       print(f'{city_indices[index]}' '. ', city_names[index])

它的输出:

  1. 布宜诺斯艾利斯
  2. 多伦多
  3. 马拉喀什
  4. 阿尔伯克基
  5. 洛斯卡沃斯
  6. 格林维尔
  7. 群岛海
  8. 平昌
  9. 瓦拉瓦拉谷
  10. 萨利纳岛
  11. 索尔塔
  12. 伊瓜苏瀑布

这就是我卡住的地方。我不知道如何以 1. 开始列表并以 12 结束,或者如何将整个内容放入 names_and_ranks = []

【问题讨论】:

    标签: list indexing


    【解决方案1】:

    只需将 1 加到 city_indices[index]:

    for index in list(range(0,len(city_names))):
        print(f'{city_indices[index] + 1}' '. ', city_names[index])
    

    输出:

    1.  Buenos Aires
    2.  Toronto
    3.  Marakesh
    4.  Albuquerque
    5.  Los Cabos
    6.  Greenville
    7.  Archipelago Sea
    8.  Pyeongchang
    9.  Walla Walla Valley
    10.  Salina Island
    11.  Solta
    12.  Iguazu Falls
    

    【讨论】:

    • 我一定会这样做的,Sushil。我仍然不确定如何将其全部放入 names_and_ranks = [ ]
    • 你能详细说明你想做什么吗?
    • 我想出了这个解决方案:names_and_ranks = [ ] for index in range(0,len(cities)): names_and_ranks.append(f'{city_indices[index] + 1}' + '。 ' + city_names[index]) print(names_and_ranks) 看起来效果不错。让我知道这是否还不够清楚。感谢您的帮助。
    • 对不起@Sushil,直到现在才检查您的答案是否正确。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2011-11-06
    • 1970-01-01
    • 2021-03-31
    • 2019-12-23
    • 2022-12-09
    • 1970-01-01
    相关资源
    最近更新 更多