Skip to main content
 首页 » 编程设计

python之我如何将变量 names_and_ranks 分配给列表,每个元素等于城市名称及其对应的排名

2024年11月24日9Terrylee

city_indices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] 
 
city_names = ['Buenos Aires', 
 'Toronto', 
 'Pyeongchang', 
 'Marakesh', 
 'Albuquerque', 
 'Los Cabos', 
 'Greenville', 
 'Archipelago Sea', 
 'Walla Walla Valley', 
 'Salina Island', 
 'Solta', 
 'Iguazu Falls'] 

对于给定的数据(city_indices 和 city_names),我想将变量 names_and_ranks 分配给一个列表,每个元素等于城市名称及其对应的排名。例如,通过使用 for 循环和列表(city_indices 和 city_names),第一个元素是“1. Buenos Aires”,第二个元素是“2. Toronto”。

下面是我写的代码,但仍然没有得到我想要的结果,如下例所示。

for city_indices in list(range(0, len(city_names))): 
print(city_indices+1, city_names[city_indices]) 

例如,我希望 names_and_ranks 应该返回如下值

names_and_ranks = [] 
 
names_and_ranks[0] # '1. Buenos Aires' 
names_and_ranks[1] # '2. Toronto' 
names_and_ranks[-1] # '12. Iguazu Falls' 

我目前正在学习Python,在这一步卡了5个小时.. 任何建议都会有所帮助!

谢谢!

请您参考如下方法:

应该有几种方法,包括使用字符串格式的列表理解:

names_and_ranks = ["%s. %s" % (i+1, name) for i, name in zip(city_indices, city_names)] 

或者如果 city_names 已经在订单中,则使用 enumerate 而不是 zip:

names_and_rank = ["%s. %s" % (i, name) for i, name in enumerate(city_names, 1)] 

两者输出相同:

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