zoukankan      html  css  js  c++  java
  • Python循环语句for的实际运用方法案例

    Python循环语句for的实际运用方法案例

    for循环
    for循环可以用来遍历某一对象(遍历:通俗点说,就是把这个循环中的第一个元素到最后一个二元素以此访问一遍)。

    1、for循环使用情景

    我们想要某个操作重复执行且循环次数已知是可以使用for循环;
    所有否循环均可以用while实现。
    2、语法格式

    for i in 一组值: #一组值可以是除数字以外的基本类型 要执行的操作

    3、for循环操作实例

    for循环可遍历除数字以外的数据基本类型,如字符串,元组,列表,集合,字典,文件等。我们还可以通过序列索引进行遍历。具体操作如下所示:

    ①for循环遍历字符串

    #for循环遍历字符串
    str='abc'
    for i in str:
        print(i)
     
    结果如下:
    a
    b
    c

    ②for循环遍历元组

    tup1=(31,29,31,30,31,30,31,31,30,31,30,31)
    for i in tup1:
        print(i,end=' ')   #end=' ' 不换行
     
    结果如下:
    31 29 31 30 31 30 31 31 30 31 30 31

    ③for循环遍历列表

    Fruits=['apple','orange','banana','grape']
    for fruit in Fruits:
        print(fruit)
     
    结果如下:
    apple
    orange
    banana
    grape

    ④for循环遍历集合

    set1={'lisi',180,60,99}    
    for i in set1:
        print(i)
     
    结果如下:
    lisi
    99
    180
    60

    ⑤for 循环遍历字典

    注意:Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。

    dict1={'name':'lisi','height':180,'weight':60,'score':99}
    for k,v in dict1.items():    #遍历字典dict1中的键值对  
        print(k,'--->',v)
    print('--------------')  
    for k in dict1.keys():       #遍历字典dict1中所有的键
        print(k)
    print('--------------')     
    for v in dict1.values():     #遍历字典dict1中所有的值 
        print(v)
     
    结果如下:
    name ---> lisi
    height ---> 180
    weight ---> 60
    score ---> 99
    --------------
    name
    height
    weight
    score
    --------------
    lisi
    180
    60
    99

    ⑥遍历文件

    for content in open("1.txt"):   #当前目录下的1.txt
        print(content)
     
    结果如下:
    朝辞白帝彩云间,千里江陵一日还。
     
     
     
    两岸猿声啼不住,轻舟已过万重山。

    ⑦for循环实现1到9连乘

    sum = 1
    for i in list(range(1,10)):   #range序列含左不含右
        sum *= i
    print("1*2...*9 =",sum)
     
    结果如下:
    1*2...*9 = 362880

    ⑧除以上之外,我们还可以通过序列索引进行遍历

    range的用法: range(5)——>1个参数,从0开始到5不包含5(即含左不含右);range(5,15)——>2个参数,从5开始到15不包含15;range(5,55,5)——>3个参数,从5开始到55不包含55,最后的参数5是步长。

    下面实例我们使用内置函数len()和range();函数len()返回列表的长度,即元素个数。range返回一个整数序列。
     

    fruits = ['banana','apple','mango','grape']
    for index in range(len(fruits)):
       print('当前水果 :', fruits[index])
     
    结果如下:
    当前水果 : banana
    当前水果 : apple
    当前水果 : mango
    当前水果 : grape

    原文链接:https://blog.csdn.net/python6_quanzhan/article/details/106362766

  • 相关阅读:
    几个新角色:数据科学家、数据分析师、数据(算法)工程师
    人类投资经理再也无法击败电脑的时代终将到来了...
    Action Results in Web API 2
    Multiple actions were found that match the request in Web Api
    Routing in ASP.NET Web API
    how to create an asp.net web api project in visual studio 2017
    网站漏洞扫描工具
    How does asp.net web api work?
    asp.net web api history and how does it work?
    What is the difference between a web API and a web service?
  • 原文地址:https://www.cnblogs.com/LQZ888/p/13094551.html
Copyright © 2011-2022 走看看