#!/uer/bin/env python # _*_ coding: utf-8 _*_ #格式1 a = 'abc' for i in range(len(a)): print a[i],'(%d)'% i a (0)b (1)c (2) #格式2 for A,i in enumerate('abc'): print i,A a 0b 1c 2 #格式2.1 b = raw_input('wartyouname:') for i,j in enumerate(b): print b[i],'
Q: for i in range(len(shape)/2):TypeError: 'float' object cannot be interpreted as an integer A: for i in range(len(shape)//2): 参考 1. https://blog.csdn.net/weixin_39223665/article/details/79485643; 完
range()是列表, xrange()是迭代 >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print i, a[i] ... 0 Mary 1 had 2 a 3 little 4 lamb 然而,在大部分情况下使用enumerate()函数会更加方便,请参见循环的技巧.
len()函数返回字符串.列表.字典.元组等长度 eg1:计算字符串的长度: >>>s='hello good boy doiido' >>>len(s) >>>21 eg2:计算列表的元素个数: name=['zhu' , 'han' , 'shi'] >>>l=['h','e','l','l','o'] age=[21,22,23] >>>len(l) for i in range(len(name)): 5 p
s = ['a','b','c','d','e'] for i in range(len(s)):... if i < len(s)-1:... print s[i] abcd for i in range(len(s)):... if i < len(s)-1:... print s[i+1]...bcde for i in range(len(s)):... if i < len(s)-1:... print s
在迭代中enumerate比range更能灵活,一般情况下尽量用erumerate,下面举例说明: 先来看range的使用: city_list = ['beijing', 'shanghai', 'tianjing', 'wuhan'] # 用range将元素打印出来 # 直接打印,不用range for city in city_list: print('this is %s' % city) # 用下标打印 for i in range(len(city_list)): city = ci