python的for循环用法 您所在的位置:网站首页 python for循环 i加 python的for循环用法

python的for循环用法

2024-06-18 19:59| 来源: 网络整理| 查看: 265

在python,for的基本使用方法如下

for item in sequence: expression

其中sequence 为可迭代的对象,item 为序列中的每个对象 可以分为以下两类:

目录 1 一类是列表list,元组tuple,字典dict,set集合,str字符串等的集合数据类型。1.1 对于列表,元组,集合以及字符串1.2 对于字典1.3 对于range()1.4 其它用法 2 一类是generator,包括生成器和带yield的generator function。3 列表生成式

1 一类是列表list,元组tuple,字典dict,set集合,str字符串等的集合数据类型。 1.1 对于列表,元组,集合以及字符串 List = [1,"a",3,4,5] for item in List: print(item, end=" ") Tuple = (1,"a",3,4,5) for item in Tuple: print(item, end=" ") Set = {1,"a",3,4,5} for item in Set: print(item, end=" ") Str = '1a345' for item in Str: print(item, end=" ") #这三个循环的结果都是一样的 #1 a 3 4 5 1.2 对于字典

对于字典,如果直接使用for循环只会输出键

Dict = {1:"a",2:"b",3:"c"} for item in Dict: print(item, end=" ") #结果 #1 2 3

如果想要输出值或者同时输出键和值,就要添加.values()和.items()

Dict = {1:"a",2:"b",3:"c"} for item in Dict.values(): print(item) #结果 #a #b #c Dict = {1:"a",2:"b",3:"c"} for item in Dict.items(): print(item) #结果 #(1, 'a') #(2, 'b') #(3, 'c') 1.3 对于range()

for循环也经常和range搭配使用,range有三种用法 1.range(start,stop) 其中start是序列的起始值,stop是序列的结束至,但不包括该值,即[start,stop)

for i in range(0,2): print(i) #结果 #0 #1

2.range(stop),相当于range(0,stop)

for i in range(2): print(i) #结果 #0 #1

3.range(start,stop,step) step 代表的为步长。表示以start为起点,step为步长的等差数列,直至数列等于或者大于 stop

for i in range(1,6,2): print(i) #结果 #1 #3 #5 1.4 其它用法

如果想用for循环输出序列的元素同时指出该元素的下标时,可以使用enumerate()函数

List = [1,"a",3,4,5] for i, item in enumerate(List): print(i,item) #0 1 #1 a #2 3 #3 4 #4 5

可以使用isinstance()判断一个对象是否是可迭代的对象:

List = [1,"a",3,4,5] Int = 1 from collections.abc import Iterable print(isinstance(List, Iterable)) print(isinstance(Int, Iterable)) #True #False 2 一类是generator,包括生成器和带yield的generator function。

先通过for循环生成一个生成器(generator),可以通过for循环输出生成器的内容

List = [1,"a",3,4,5] gen = (item for item in (List)) print(type(a)) print(a) for item in gen: print(item) #结果 # # #1 #a #3 #4 #5

创建带yield的generator function。例如,斐波拉契数列的生成器

def fib(max): n, a, b = 0, 0, 1 while n


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有