Python 我被卡住了,无法正确整合列表
我被卡住了-(已经尝试了一天半了-我不知道如何用python编写代码来克服它在底部的中断-请指导我如何设置它以获得成功。谢谢 我们的城市列表包含关于前12个城市的信息。对于我们即将进行的迭代任务,有一个数字0到11的列表将非常有用。使用我们所知道的关于len和Range的信息生成一个数字1到11的列表。将其分配给一个名为city_Index的变量Python 我被卡住了,无法正确整合列表,python,loops,variables,Python,Loops,Variables,我被卡住了-(已经尝试了一天半了-我不知道如何用python编写代码来克服它在底部的中断-请指导我如何设置它以获得成功。谢谢 我们的城市列表包含关于前12个城市的信息。对于我们即将进行的迭代任务,有一个数字0到11的列表将非常有用。使用我们所知道的关于len和Range的信息生成一个数字1到11的列表。将其分配给一个名为city_Index的变量 len(cities) range(0, len(cities)) city_indices=list(range(0,len(cities))) c
len(cities)
range(0, len(cities))
city_indices=list(range(0,len(cities)))
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']
for index in list(range(0, len(city_names))):
print(city_names[index])
Buenos Aires
Toronto
Pyeongchang
Marakesh
Albuquerque
Los Cabos
Greenville
Archipelago Sea
Walla Walla Valley
Salina Island
Solta
Iguazu Falls
您的任务是将变量名和排名分配给一个列表,每个元素都等于城市名称及其对应的排名。例如,第一个元素是“1.布宜诺斯艾利斯”,第二个元素是“2.多伦多”。使用For循环并列出城市索引和城市名称来完成此任务
for index in [0,1,2,3,4,5,6,7,8,9,10,11]:
print(city_indices[index]+".", city_names[index])
错误:
TypeErrorTraceback(最近一次呼叫上次)in()
[0,1,2,3,4,5,6,7,8,9,10,11]中的索引为1:
---->2打印(城市索引[索引]+”,城市名称[索引]) TypeError:不支持+:“int”和“str”的操作数类型 对问题的答复: 修正问题中的代码: 使用从0(而非1)索引的城市索引: 使用
zip
:
通过列表理解
:
更好的方法:
枚举列表
:
for index in [0,1,2,3,4,5,6,7,8,9,10,11]:
print(f'{index}. {city_names[index]}')
for index in city_indices:
print(f'{index}. {city_names[index]}')
city_indices = list(range(1, len(city_names)+1))
names_and_ranks = list()
for i, x in zip(city_indices, city_names):
names_and_ranks.append(f'{i}. {x}')
names_and_ranks = [f'{i}. {x}' for i, x in zip(city_indices, city_names)]
names_and_ranks = [f'{i}. {x}' for i, x in enumerate(city_names, start=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']