python中循环的写法 for

最近倒腾python,希望能坚持下去吧

发现了个叫codecademy的网站,还不错http://www.codecademy.com/courses/python-beginner-en-IZ9Ra/0/1?curriculum_id=4f89dab3d788890003000096


1. list

names = ["Adam","Alex","Mariah","Martine","Columbus"]
for name in names:
    print name

在上面这段中,names是一个list, 它的构成是[ ],每个元素之间用,分隔

name表明names中的每一个变量,注意for的那一条语句要加冒号


2. dictionary

webster = {
	"Aardvark" : "A star of a popular children's cartoon show.",
    "Baa" : "The sound a goat makes.",
    "Carpet": "Goes on the floor.",
    "Dab": "A small amount."
}

# Add your code below!
for key in webster:
    print webster[key]

在这段中,webster是一个dictionary,由{ }构成,每个元素之间用,分隔

每个元素由一对key和value构成,中间由:分隔

"Aardvark" : "A star of a popular children's cartoon show."

上一条语句中key是"Aardvark"  value是"A star of a popular children's cartoon show."

for循环中的变量是每一个元素的key,所以要打印对应的value时需要webster[key]这种方式来访问


3.string

for letter in "Codecademy":
    print letter

对于string来说,相当于每一个字母为元素构成的list

所以用for来访问的时候相当于访问的是每一个字母


4. range()

n=[1,2,3,4,5]
for i in range(0, len(n)):
    n[i] = n[i] * 2


5.enmerate 是一个build in function 可以同时提供 index和item

choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item
输出;

Your choices are:
1 pizza
2 pasta
3 salad
4 nachos
None

6. zip  zip will create pairs of elements when passed two lists, and will stop at the end of the shorter 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):
    # Add your code here!
    print max(a,b)

输出:

3
9
17
15
30

7 python中 for和while 都有else

但是不同在于 for循环的else 只有在for正常退出时才会执行,当for循环由break退出时不执行

 the else statement is executed after the for, but only if thefor ends normally—that is, not with abreak.



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值