【问题标题】:How to iterate over the elements of two lists at the same time in Python如何在 Python 中同时遍历两个列表的元素
【发布时间】:2021-07-26 16:36:09
【问题描述】:

我在 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 循环首先分别读取“Mary”和“she”,然后是“Joe”和“he”?

提前谢谢你。

【问题讨论】:

  • 您可以使用 zip、下方或 enumerate。另外,您所说的“性别”实际上并不是性别。这是一个(人称)代词。
  • 这是一个玩具密码...谢谢!

标签: python list for-loop


【解决方案1】:

为什么,你可以选择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

【讨论】:

  • 谢谢@Sujay!
  • @Manuela。最受欢迎的。如果它解决了问题,请考虑支持并接受答案
  • 我投了赞成票,但我只能在 7 分钟内接受答案(它告诉我)@Sujay
  • @Manuela,没问题
  • Manuela 的名字很有意义,您将其更改为 ij。为什么,哦,为什么?请改回persongender
猜你喜欢
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
相关资源
最近更新 更多