python中实现循环指定次数:
count=0
for item in list:
print item
count +=1 ? ?if count % 10 == 0:
print 'did ten'
或:
for count in range(0,len(list)):
print list[count] ? ?if count % 10 == 0:
在Python的for循环里,循环遍历可以写成:
扩展资料:
Python 注意事项:
①.、tuple:元组
(1)元组一旦初始化就不可修改.不可修改意味着tuple更安全.如果可能,能用tuple代替list就尽量用tuple.
a.获取value值:dict['key'],若key不存在,编译器就会报错KeyError.避免方法:
一是通过 in 判断 key 值是否在dict中:
'key' in dict # 返回True 或 False.
二是通过 dict 的函数get():
dict.get('key') # 返回 value 值 或 None.
编写循环的技巧,for循环包含了常见的计数器式循环.由于通常for循环比while循环更容易写,也执行得更快,所以for循环一般是你遍历序列或其他可迭代对象时的首选.事实上,作为一条通用法则,你应该克制在Python中使用计数方式的诱惑——Python提供的迭代工具,能帮你把像C这样低级语言中循环集合体的工作自动化.不过,有些情况下你还是需要以更为特定的方式进行迭代.例如,如果你需要在列表中每隔一个元素或每隔两个元素进行访问,或是要同时修改列表呢?如果在同一个for循环内,并行遍历一个以上的序列呢?如果你也需要进行索引呢?
for ... in ...
//?for?...?in?字符串
for?i?in?'abc':
print(i)
'''
a
b
c
//?for?...?in?数组
for?i?in?['a',?'b',?'c']:
//?for?...?in?元组
for?i?in?('a',?'b',?'c'):
//?for?...?in?字典(得到的是字典的key)
print(k)
姓名
学号
//?for?...?in?字典.items()(得到的是字典的key,?value)
print(k,?v)
姓名?小明
for ... in range(...)
//?for?...?in?range(num)
'''??
倒叙
又想得到遍历次数,又想得到数组值
for i,e in enumerate(array):
print(i,?e)
列表生成式
[...for ... in array]]
//相当于
list?=?[]
list.append(x?*?x)
print(list)