1

希望有人可以在这里帮助我。我在 Python 的 for 循环中使用了 for 循环。那是一个嵌套循环,我想将结果映射一次。目前结果正确显示一次,然后错误地重复。这是我的代码片段。

for country in ["USA", "Nigeria", "Germany", "India", "Britain"]:
    for code in ["+1", "+234", "+49", "+91", "+44"]:
        print(country, code)
        
print("Done")

我想要达到的结果就是这个。

USA +1
Nigeria +234
Germany +49
India +91
Britain +44
Done!

但我现在得到的是这个。

USA +1
USA +234
USA +49
USA +91
USA +44
Nigeria +1
Nigeria +234
Nigeria +49
Nigeria +91
Nigeria +44
Germany +1
Germany +234
Germany +49
Germany +91
Germany +44
India +1
India +234
India +49
India +91
India +44
Britain +1
Britain +234
Britain +49
Britain +91
Britain +44
Done

有没有办法可以改进它并获得预期的结果?我会感谢你的帮助。

4

3 回答 3

4

您可以压缩国家和代码以匹配相应的元素:

countries = ["USA", "Nigeria", "Germany", "India", "Britain"]
codes = ["+1", "+234", "+49", "+91", "+44"]

for country, code in zip(countries, codes):
    print(country, code)

(或更好的格式:)print(f"{country} {code}")

当在循环内循环时,您会打印每个国家/地区的每个代码,这就是您在当前输出中看到的内容。

Zip 就像它听起来的那样,即它充当拉链:

list(zip(countries, codes))

[("USA", "+1"), ("Nigeria", "+234"), ...]
于 2021-07-15T13:29:07.483 回答
2

这将起作用:

countries = ["USA", "Nigeria", "Germany", "India", "Britain"];
codes = ["+1", "+234", "+49", "+91", "+44"];

for i in range(len(countries)):
    print(countries[i], codes[i])
于 2021-07-15T13:34:57.097 回答
1

我不确定这是你在等待什么,但这里有一个发送你正在等待的结果的代码:

country = ["USA", "Nigeria", "Germany", "India", "Britain"]
code = ["+1", "+234", "+49", "+91", "+44"]
for i in range(4):
    print(country[i], code[i])
print('done')
于 2021-07-15T13:34:40.937 回答