for i in range(len(nums)): print(i, nums[i]) print("---") for i, num in enumerate(nums): print(i, num) 1. 2. 3. 4. 5. 6. 7. 二、while 循环 如果不知道具体的循环次数,使用while循环更合适。 while循环 通过一个条件表达式来控制循环,表达式的值为 True(即条件满足)则循环继续,表...
for与break、continue、else的用法与while类似 #for+enumerate 索引+值 nums = [111,222,333,444,555] i =0 whilei<len(nums): print(i,nums[i]) i +=1 fori,numinenumerate(nums): print(i,num)
nums = [111, 222, 333, 444, 555]fornuminnums:ifnum == 333:#breakcontinueprint(num)else:print('===') 5.(1)让某段代码重复运行3次-》while循环实现如下 i =0whilei < 3:print('hello1')print('hello2')print('hello3') i+= 1 (2)让某段代码重复运行3次-》for循环实现如下 forxinra...
foridx, valinenumerate(ints):print(idx, val) Run Code Online (Sandbox Code Playgroud) 查看PEP 279了解更多信息. 正如Aaron在下面指出的那样,如果你想获得1-5而不是0-4,则使用start = 1.(48认同) @用户2585501。它确实:“for i in range(5)”或“for i in range(len(ints))”将执行迭代索引的...
deffind_max_and_second_max(nums):iflen(nums)<2:returnNone,Nonemax_val=second_max=float('-inf')max_index=second_max_index=-1fori,numinenumerate(nums):ifnum>max_val:second_max,second_max_index=max_val,max_index max_val,max_index=num,ielifnum>second_maxandi!=max_index:second_max,se...
2. 当你有一个列表,想要同时得到索引和元素时,可以用`enumerate()`函数和`for...in`搭配。这就好比你不仅知道每个小物品(元素),还知道它在盒子(列表)里的位置(索引)。比如: - 对于列表`numbers = [10, 20, 30]`: ```python numbers = [10, 20, 30] for index, num in enumerate(numbers): prin...
for i in range(1, 10, 2): print(i) ``` 运行结果为: ``` 1 3 5 7 9 ``` 在这个例子中,我们使用range()函数生成了一个1到9的数值序列,步长为2,然后使用for循环遍历这个数值序列并输出。这展现了for循环与range()函数结合的使用。 2. 使用enumerate()函数同时遍历索引和元素 ```python fruits ...
for idx, word in enumerate(words): print(f"{idx}: {word}") With the help of theenumeratefunction, we print the element of the list with its index. $ ./for_loop_index.py 0: cup 1: star 2: monkey 3: bottle 4: paper 5: door ...
for num in nums[:]: if num > 5: nums.pop(nums.index(num)) print(nums) 1. 2. 3. 4. 5. 6. 结果: [3, 3, 4, 1] while 循环语句,与if相比,若满足条件,一直运行,而不是一次。 while expression: something need to repeat 1. ...
for i, j in enumerate(sequence): print(i,j) 二、使用list.append()模块对质数进行输出。 #!/usr/bin/python # -*- coding: UTF-8 -*- # 输出 2 到 100 简单质数 prime = [] for num in range(2,100): #2-100内循环 for i in range(2,num):# 根据因子迭代 if num%i == 0: # 确...