如何让列表索引的输出从1开始?

问题描述 投票:0回答:2

我有 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
2个回答
1
投票

只需在

city_indices[index]
上加 1:

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

0
投票

这是另一种表达方式。

names_and_ranks = []
i = 1
for name in city_names:
    names_and_ranks.append("%s. %s" % (i, name))
    i += 1
names_and_ranks
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.