栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Python

for 循环

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

for 循环

1. for i in range() 循环:

for 循环: 已知循环次数的情况下, 需要多次重复代码块时使用

while 循环: 终止条件决定何时停止

range 控制循环次数,range(start,stop, step)

for i in range(6): -- stop = 6 

print(i) --- 0,1,2,3,4,5

for i in range(20, 25):

print(i) -- 20,21,22,23,24

for i in range(50, 0, -10):

print(i) -- 50, 40, 30, 20, 10 

作为循环固定次用法:

for i in range(3):

      sum += number

return sum 

2. range(len()) 用在list  (is better expressed with enumerate)

list = ['a', 'b', 'c']

for i in list:

      print(i) ---- a b c

等同于

list = ['a', 'b', 'c']

for i in range(len(list)):

     print(list[i]) ---- a b c

this is useful when you want to modify the list at certain positions

i.e. 

list = ['a', 'b', 'c', 'd', 'e']

for i in range(len(list)):

     if list[i] in 'aeiou':

        list[i] = 'vowel'

      else:

         list[i] = 'consonant'

list == ['vowel' 'consonant', 'consonant', 'consonant', 'vowel']

for i in range() iterates through numbers. For element in list iterates through whatever is in the list. for i in range(len(list)) iterates through numbers which can be used for index access of list. 

3. for in list 循环

words = ['a', 'b', 'c']

for i in words:

     print(i) -- a b c

列表和其它的“序列”数据类型 比如 strings以及tuples(元组)都常常被用于循环,因为他们有“可被迭代”的特性。你可以组合这些数据结构与range()协同,去在列表中增加项目

for i in range(len(words)):

     words.append('d')

print(words)---a,b,c,d,d,d

此处将'd'作为占位字符串,在words列表中增加了len(words)次'd'(len(words)为起始时words列表中项目的总数/列表原长)

用for循环构建一个列表:

list = []

for i in range(3):

      list.append(i)

print(list) - []

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1038334.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号