python中循环的写法 for

2023-01-31 01:01:12 python 循环 写法

最近倒腾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.



相关文章