• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

jwang106


脚踏实地,日拱一卒。 建立新的神经链接,可不像公园散步那样简单。
  • 博客园
  • 联系
  • 管理

View Post

如何在一个for语句中迭代多个对象(2.7)

如何在一个for语句中迭代多个对象

总结:

并行迭代使用zip(l1, l2, l3)

每次迭代从3个列表里各取一个数据

串行迭代使用itertools.chain(l1, l2, l3)

相当于把3个里边拼接成了一个列表再迭代

并行迭代:使用zip 某班4个人各科成绩的迭代

from random import randint
l1 = ['jwang', 'Tom', 'Jerry', 'Liming']
l2 = [randint(60, 100) for x in range(4)]
l3 = [randint(60, 100) for x in range(4)]
l4 = [randint(60, 100) for x in range(4)]

print(l1)
print(l2)
print(l3)
print(l4)

for name, math, english, physics in zip(l1, l2, l3, l4):
    print("name:%s, math:%s, english:%s, physics:%s" % (name, math, english, physics))

output:

['jwang', 'Tom', 'Jerry', 'Liming']
[64, 69, 94, 93]
[81, 89, 64, 80]
[69, 94, 81, 62]
name:jwang, math:64, english:81, physics:69
name:Tom, math:69, english:89, physics:94
name:Jerry, math:94, english:64, physics:81
name:Liming, math:93, english:80, physics:62

如果列表长度不一样也能迭代

from random import randint
l1 = ['jwang', 'Tom', 'Jerry', 'Liming']
l2 = [randint(60, 100) for x in range(4)]
l3 = [randint(60, 100) for x in range(4)]
l4 = [randint(60, 100) for x in range(3)]

print(l1)
print(l2)
print(l3)
print(l4)

for name, math, english, physics in zip(l1, l2, l3, l4):
    print("name:%s, math:%s, english:%s, physics:%s" % (name, math, english, physics))

output:

['jwang', 'Tom', 'Jerry', 'Liming']
[92, 66, 91, 75]
[72, 92, 100, 77]
[71, 67, 98]
name:jwang, math:92, english:72, physics:71
name:Tom, math:66, english:92, physics:67
name:Jerry, math:91, english:100, physics:98

串性迭代 使用chain

for x in chain([1, 2, 3, 4],['a', 'b', 'c']):
    print(x)

output:

1
2
3
4
a
b
c

4个班 每个班的英语成绩各存一个列表,统计全学年成绩高于90的人数

from itertools import chain
l1 = [randint(60, 100) for x in range(4)]
l2 = [randint(60, 100) for x in range(4)]
l3 = [randint(60, 100) for x in range(4)]
l4 = [randint(60, 100) for x in range(3)]

print(l1)
print(l2)
print(l3)
print(l4)

count = 0
for x in chain(l1, l2, l3, l4):
    if x>90:
        count += 1
print(count)

output:

[66, 94, 66, 73]
[98, 90, 90, 60]
[69, 83, 75, 61]
[71, 83, 68]
2

posted on 2019-02-03 15:34  jwang106  阅读(223)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3