下面是代码
river_and_countries = {
'Nile' : 'egypt',
'Amazon' : 'Brazil',
'yangtze' : 'china',
'mississippi' : 'united states of america',
'yenisei' : 'russia',
'ob' : 'russia',
'huang' : 'china',
}
num = len(river_and_countries) + 1
n = [value for value in range(1, num)]
print(f"Following are the longest rivers in the world and their countries (by order):\n")
for x in n:
for river, country in river_and_countries.items():
if country == 'united states of america':
print(f"{x}. River {river.title()} is in the {country.title()}.")
else:
print(f"{x}. River {river.title()} in {country.title()}.") 我想打印前七条最长河流的列表,并在前面添加一个数字,但对于每个数字,它都会重复该列表。
如何为每条河流分配一次编号?
当前输出:
Following are the longest rivers in the world and their countries (by order):
1. River Nile in Egypt.
1. River Amazon in Brazil.
1. River Yangtze in China.
1. River Mississippi is in the United States Of America.
1. River Yenisei in Russia.
1. River Ob in Russia.
1. River Huang in China.
2. River Nile in Egypt.
2. River Amazon in Brazil.
2. River Yangtze in China.
2. River Mississippi is in the United States Of America.
2. River Yenisei in Russia.
2. River Ob in Russia.
2. River Huang in China.
3. River Nile in Egypt.
3. River Amazon in Brazil.
3. River Yangtze in China.
3. River Mississippi is in the United States Of America.
3. River Yenisei in Russia.
3. River Ob in Russia.
3. River Huang in China.
4. River Nile in Egypt.
4. River Amazon in Brazil.
4. River Yangtze in China.
4. River Mississippi is in the United States Of America.
4. River Yenisei in Russia.
4. River Ob in Russia.
4. River Huang in China.
5. River Nile in Egypt.
5. River Amazon in Brazil.
5. River Yangtze in China.
5. River Mississippi is in the United States Of America.
5. River Yenisei in Russia.
5. River Ob in Russia.
5. River Huang in China.
6. River Nile in Egypt.
6. River Amazon in Brazil.
6. River Yangtze in China.
6. River Mississippi is in the United States Of America.
6. River Yenisei in Russia.
6. River Ob in Russia.
6. River Huang in China.
7. River Nile in Egypt.
7. River Amazon in Brazil.
7. River Yangtze in China.
7. River Mississippi is in the United States Of America.
7. River Yenisei in Russia.
7. River Ob in Russia.
7. River Huang in China.
[Finished in 0.2s]发布于 2020-05-28 23:17:17
删除嵌套的for循环,并使用enumerate()函数生成数字:
print(f"Following are the longest rivers in the world and their countries (by order):\n")
for i, (river, country) in enumerate(river_and_countries.items(), start=1):
if country == 'united states of america':
print(f"{i}. River {river.title()} is in the {country.title()}.")
else:
print(f"{i}. River {river.title()} in {country.title()}.")Following are the longest rivers in the world and their countries (by order):
1. River Nile in Egypt.
2. River Amazon in Brazil.
3. River Yangtze in China.
4. River Mississippi is in the United States Of America.
5. River Yenisei in Russia.
6. River Ob in Russia.
7. River Huang in China.https://stackoverflow.com/questions/62065875
复制相似问题