for循环
1. 字符串操作
输出字符串中的每个字符
word = 'love'
for c in word:
print c
以上代码输出:
若代码如下:
word = 'love'
for c in word:
print c,
比上面的代码多了逗号,则输出:
逗号的作用是:在一行输出
2. enumerate函数
返回一个enumerate类型,参数一般是可以遍历的类型,比如list, string等
list = ['num1', 'num2', 'num3']
for index, item in enumerate(list):
print index, item
以上代码输出:
相比于for item in list:
增加了索引,从0开始。
3. zip函数
zip函数用来同时迭代两个以上的list,以元素少的list为结束:
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
if a > b:
print a
else:
print b
以上代码输出:
4. while/else和for/else
i = 3
while i > 0:
print 'while', i
i -= 1
else:
print 'else'
以上代码输出:当while 正常结束 时,else被执行
但是,当循环非正常结束时(break),else不执行
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
if f == 'tomato':
print 'A tomato is not a fruit!' # (It actually is.)
break
print 'A', f
else:
print 'A fine selection of fruits!'
以上代码输出:else没有执行
5. int, string相互转换
#int to string
num = 12345
string = str(num)
#string to int
string = '12323'
num = int(string)
6. list, string相互转换
#string to list
str1 = "12345"
list1 = list(str1)
print list1 #输出:['1', '2', '3', '4', '5']
str2 = "123 love aaa"
list2 = str2.spilt()
print list2 #输出: ['123', 'love', 'aaa']
str3 = "www.google.com"
list3 = str3.spilt('.')
print list3 #输出: ['www', 'google', 'com']
#list to string
str4 = "".join(list3)
print str4 #输出: wwwgooglecom
str5 = ".".join(list3)
print str5 #输出: www.google.com
str6 = " ".join(list3)
print str6 #输出: www google com