while
语法结构,用:隔开
while condition :
expression
x = 1
while x < 4 :
print(x)
x = x + 1
# Initialize offset
offset = 8
# Code the while loop
while offset != 0:
print("correcting...")
offset = offset-1
print(offset)
output
output:
correcting...
7
correcting...
6
correcting...
5
correcting...
4
correcting...
3
correcting...
2
correcting...
1
correcting...
0
while和if的混搭
# Initialize offset
offset = -6
# Code the while loop
while offset != 0 :
print("correcting...")
if offset > 0 :
offset = offset -1
else :
offset = offset + 1
print(offset)
for循环
List里的for循环
# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Code the for loop
for i in areas :
print(i)
enumerate, 可以同时输出变量的序列和数值
l = ['Alice', 'Bob', 'Charlie']
for name in l:
print(name)
# Alice
# Bob
# Charlie
for i, name in enumerate(l):
print(i, name)
# 0 Alice
# 1 Bob
# 2 Charlie
默认是从0开始,可以指定从1或者从任意数字开始。
for i, name in enumerate(l, 1):
print(i, name)
# 1 Alice
# 2 Bob
# 3 Charlie
自定义输出格式
# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Code the for loop
for index, area in enumerate(areas) :
print("room " + str(index+1) + ": " + str(area))
output
room 1: 11.25
room 2: 18.0
room 3: 20.0
room 4: 10.75
room 5: 9.5
双层list的for循环也是毫不费力
# house list of lists
house = [["hallway", 11.25],
["kitchen", 18.0],
["living room", 20.0],
["bedroom", 10.75],
["bathroom", 9.50]]
# Build a for loop from scratch
for x, y in house:
print("the " + str(x) + " is " + str(y) + " sqm" )
the hallway is 11.25 sqm
the kitchen is 18.0 sqm
the living room is 20.0 sqm
the bedroom is 10.75 sqm
the bathroom is 9.5 sqm
Dictionary里的for循环
和list不一样的是需要用到items()这个指令
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin',
'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }
# Iterate over europe
for k, v in europe.items() :
print("the capital of " + k + " is " + v)
Numpy array里的for循环
numpy array可以是1D也可以是2D,1D的话和list一样,2D的话要用到np.nditer,把两列按照一列来显示。
# Import numpy as np
import numpy as np
# For loop over np_height
for x in np_height :
print(str(x) + " inches")
# For loop over np_baseball
for val in np.nditer(np_baseball) :
print(val)
Dataframe里的for循环
iterrows()按照行来分析。
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
cars.head()
# Iterate over rows of cars
for lab, row in cars.iterrows() :
print(lab)
print(row)
output
cars.head()
cars_per_cap country drives_right
US 809 United States True
AUS 731 Australia False
JPN 588 Japan False
IN 18 India False
RU 200 Russia True
output:
US
cars_per_cap 809
country United States
drives_right True
Name: US, dtype: object
AUS
cars_per_cap 731
country Australia
drives_right False
Name: AUS, dtype: object
JPN
cars_per_cap 588
country Japan
drives_right False
Name: JPN, dtype: object
IN
cars_per_cap 18
country India
drives_right False
Name: IN, dtype: object
RU
cars_per_cap 200
country Russia
drives_right True
Name: RU, dtype: object
MOR
cars_per_cap 70
country Morocco
drives_right True
Name: MOR, dtype: object
EG
cars_per_cap 45
country Egypt
drives_right True
Name: EG, dtype: object
两种方法添加列
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
cars.head()
# Code for loop that adds COUNTRY column
for lab, row in cars.iterrows():
cars.loc[lab,"COUNTRY"] = str.upper(row["country"])
# Print cars
print(cars)
2.apply
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
cars["country"]
# Use .apply(str.upper)
for lab, row in cars.iterrows() :
cars["COUNTRY"] = cars["country"].apply(str.upper)
print(cars)