我可以在另一个 for 循环中使用第二个 for 循环,“没有读取第二个循环”从第一个 for 循环?

时间:2021-07-26 16:36:09

标签: python for-loop

我在 Python 中使用 for 循环时遇到问题。我写了这段代码:

x=5
people=['Mary','Joe']
genders=['she','he']

for person in people:
    print(person)
    for gender in genders:
        if x > 0:
            print("{} is happy".format(gender)) 

输出为:

Mary
she is happy
he is happy
Joe
she is happy
he is happy

但我希望输出是:

Mary
she is happy
Joe
he is happy

因此,我应该找到一种方法将 for 循环 for gender in genders: 放在第一个 for 循环 for person in people 的“外部”,但是在 {{1} 中按性别“读取” }.我能怎么做?或者是否有替代/更智能的方式来获得我需要的东西?

我先谢谢你。

1 个答案:

答案 0 :(得分:4)

为什么,你可以选择zip()。这是一个更简洁的解决方案。

people=['Mary','Joe']
genders=['she','he']
for person,gender in zip(people,genders):
    print(person)
    print("{} is happy".format(gender)) 

输出:

Mary
she is happy
Joe
he is happy