for循环

2019-05-23  本文已影响0人  single仔

本人只是初学阶段,在学习过程中的一些笔记。想借此平台也分享给刚刚学习的朋友,如有错的地方欢迎各位大神与高手指点。

例一:求1至100的正整数之和

sum = 0

for i in range(1,101):

    sum += i

print(sum)


例子二:99乘法表

for i in range(1, 10):

    for x in range(1, i + 1):

        print("%d * %d = %d" % (i, x, i * x), end='')


例子三:逐一开分显示d1字典中的所有元素

d1 = {'x': 123, 'y': 456, 'z': 789}

for (k, v) in d1.items():

    print(k, v)


例子四:显示d1字典中的键或者值

d1 = {'sun': '太阳', 'moon': '月亮', 'star': '星星'}

for x in d1.keys():

    print(x+'会亮(显示键)')

for x in d1.values():

    print(x+"会亮(显示值)")


例子五:逐一显示列表l1中为索引为奇数的元素

l1 = ['Sun', 'Mon', 'Tue', "Wed", 'Thu', 'Fri', 'Sat']

for i in range(1, len(l1), 2):

    print(l1[i])


例子六:将列表l1中有的而l2中没有的添加到列表l3中

l1 = [1, 2, 3, 4, 5, 6, 7]

l2 = [3, 8, 9, 1, 2]

l3 = []

for i in l1:

    if i not in l2:

        l3.append(i)

print(l3)


例子七:将removelist中有的元素从namelist中删除

namelist = ['stu1', 'stu2', 'stu3', 'sut4', 'sut5', 'sut6', 'sut7']

removelist = ['stu3', 'sut7', 'sut9']

for i in removelist:

    if i in namelist:

        namelist.remove(i)

print(namelist)


例子八:跌代器对象用for进行遍历

l1 = ['Sun', 'Mon', 'Tue', "Wed", 'Thu', 'Fri', 'Sat']

it = iter(l1)

for x in it:

    print(x)

上一篇下一篇

猜你喜欢

热点阅读