if,elif,else
if phone_balance < 5:
phone_balance += 10
bank_balance -= 10
if season == 'spring':
print('plant the garden!')
elif season == 'summer':
print('water the garden!')
elif season == 'fall':
print('harvest the garden!')
elif season == 'winter':
print('stay indoors!')
else:
print('unrecognized season')
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for city in cities:
print(city)
print("Done!")
new york city
mountain view
chicago
los angeles
Done!
Operation and Method
c++或java中for的使用
for i in range(start,end):
arr[i] #Operation
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for index in range(len(cities)):
cities[index] = cities[index].title()
New York City
Mountain View
Chicago
Los Angeles
cast = {
"Jerry Seinfeld": "Jerry Seinfeld",
"Julia Louis-Dreyfus": "Elaine Benes",
"Jason Alexander": "George Costanza",
"Michael Richards": "Cosmo Kramer"
}
for key in cast:
print(key)
Jerry Seinfeld
Julia Louis-Dreyfus
Jason Alexander
Michael Richards
只能访问key
for key, value in cast.items():
print("Actor: {} Role: {}".format(key, value))
Actor: Jerry Seinfeld Role: Jerry Seinfeld
Actor: Julia Louis-Dreyfus Role: Elaine Benes
Actor: Jason Alexander Role: George Costanza
Actor: Michael Richards Role: Cosmo Kramer
通过item获取字典的键值对,然后利用unpacking 赋值给key和value,以既访问key,又访问value
card_deck = [4, 11, 8, 5, 13, 2, 8, 10]
hand = []
# adds the last element of the card_deck list to the hand list
# until the values in hand add up to 17 or more
while sum(hand) < 17:
hand.append(card_deck.pop())
zip(list1,list2)
返回了一个迭代器
list(zip(list1,list2))
或者for item,weight in zip(items,weights)
items = ['banana','mattresses','dog kennels','machine','cheese']
weights = [15,34,42,120,5]
print(list(zip(items,weights)))
[('banana', 15), ('mattresses', 34), ('dog kennels', 42), ('machine', 120), ('cheese', 5)]
items,weights = zip(*manifest)
items = ['banana','mattresses','dog kennels','machine','cheese']
weights = [15,34,42,120,5]
manifest = []
for item, weight in zip(items,weights):
manifest.append((item,weight))
print(manifest)
items1,weights1 = zip(*manifest)
print(items1)
print(weights1)
[('banana', 15), ('mattresses', 34), ('dog kennels', 42), ('machine', 120), ('cheese', 5)]
('banana', 'mattresses', 'dog kennels', 'machine', 'cheese')
(15, 34, 42, 120, 5)
Process finished with exit code 0
items = ['banana','mattresses','dog kennels','machine','cheese']
for i,item in zip(range(len(items),items))
print(i,' ',item)
items = ['banana','mattresses','dog kennels','machine','cheese']
for i,item in zip(range(len(items)),items):
print("{} {}".format(i,item))
id | item |
---|---|
0 | banana |
1 | mattresses |
2 | dog kennels |
3 | machine |
4 | cheese |