简体   繁体   English

如何在Python中的两个列表的已建立循环中分配变量?

[英]How do I assign a variable to an established loop of two lists in Python?

I have the following for loop assigned to a set of two list indices in Python, and must set it to the variable "names_and_ranks". 我在Python中将以下for循环分配给一组两个列表索引,并且必须将其设置为变量“ names_and_ranks”。 How would I do that from here? 我将如何从这里开始?

for index in [0,1,2,3,4,5,6,7,8,9,10,11]:
    print (city_indices[index]+".",city_names[index])

This prints as follows: 打印如下:

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

The original question was: "assign the variable names_and_ranks to a list, with each element equal to the city name and it's corresponding rank. For example, the first element would be, "1. 最初的问题是:“将变量names_and_ranks分配给一个列表,每个元素等于城市名称及其对应的等级。例如,第一个元素为“ 1。 Buenos Aires" and the second would be "2. 布宜诺斯艾利斯”,第二个是“ 2。 Toronto". Use a for loop and the lists city_indices and city_names to accomplish this." “多伦多。”使用for循环并列出city_indices和city_names来完成此操作。”

for index in [0,1,2,3,4,5,6,7,8,9,10,11]:
    print (city_indices[index]+".",city_names[index])

Here are two working solutions the first uses a traditional for loop and the second uses list comprehension: 这是两个可行的解决方案,第一个使用传统的for循环,第二个使用列表理解:

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

# using a for loop
names_and_ranks = []
for index in range(12):
    names_and_ranks.append(f"{city_indices[index]}. {city_names[index]}")

# using list comprehension
names_and_ranks = [
    ". ".join([str(x) for x in item]) for item in zip(city_indices, city_names)
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM