Python Lists

suitcase = [] 
suitcase.append("sunglasses")

# Your code here!
suitcase.append("hat")
suitcase.append("dress")
suitcase.append("cellphone")


list_length = len(suitcase) # Set this to the length of suitcase

print "There are %d items in the suitcase." % (list_length)
print suitcase
#There are 4 items in the suitcase.
#['sunglasses', 'hat', 'dress', 'cellphone']
#注意append方法 
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first  = suitcase[0:2]  # The first and second items (index zero and one)

animals = "catdogfrog"
cat  = animals[:3]   # The first three characters of animals
#You can slice a string exactly like a list
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")   # Use index() to find "duck"
# Your code here!
#.index函数传回一个数字,直接将其作为.insert的第一个参数
animals.insert(duck_index, "cobra")
start_list = [5, 3, 1, 2, 4]
square_list = []

# Your code here!
for i in start_list:
    square_list.append(i ** 2)
    # 遍历startlist所有数字,把其平方传入square_list中 
square_list.sort()
print square_list    #Note that .sort() modifies the list rather than returning a new list.
backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove('dagger')# 删除list中的项backpack.pop(1)也可实现,并且会将该元素返回。即a = backpack.pop(1)  a的值为dagger
                                              # 也可以用 del(backpack[1])

List拼接

a = [1, 2, 3]
b = [4, 5, 6]
print a + b
# prints [1, 2, 3, 4, 5, 6]
#直接加起来就拼接完成




Dictionaries

#字典的使用。
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

print residents['Puffin'] 
print residents['Sloth']
print residents['Burmese Python']

An empty pair of curly braces {} is an empty dictionary, just like an empty pair of [] is an empty list.
The length len() of a dictionary is the number of key-value pairs it has. Each pair counts only once, even if the value is a list. (That's right: you can put lists inside dictionaries!)

menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair  如果key已存在,则可以修改其值为14.50

zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines  声明可换行
del zoo_animals['Unicorn']  #删除键值对

混合使用

inventory = {
    'gold' : 500,
    'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
    'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'
inventory['pouch'].sort() 

# Your code here
inventory['pocket'] = ['seashell','strange berry','lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] += 50

print inventory

打印显示结果:
{'pocket': ['seashell', 'strange berry', 'lint'], 'backpack': ['bedroll', 'bread loaf', 'xylophone'], 'pouch': ['flint', 'gemstone', 'twine'], 'burlap bag': ['apple', 'small ruby', 'three-toed sloth'], 'gold': 550}

对list和dictioary使用for循环

names = ["Adam","Alex","Mariah","Martine","Columbus"]

for i in names:
    print i  #依次打印出names当中的值,但是这种遍历方式无法修改list。
              #for i in range(len(list)):
              #     print list[i]       uses indexes to loop through the list, making it possible to also modify the list if needed. 
   

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."
}

for i in webster:
    print webster[i]  #同样是依次打印,但是注意dictionary是无序的,所以打印出的顺序不一定和上面定义的相同

Adam Alex Mariah Martine Columbus列表打印效果
A star of a popular children's cartoon show. Goes on the floor. A small amount. The sound a goat makes.字典打印效果,注意顺序的区别

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
#list of lists,可以联系二维数组来理解

def flatten(lists):
    results = []
    for numbers in lists:   #遍历外层list,即第一维数组
        for number in numbers:   #遍历内层list,即第二维数组
            results.append(number)
    return results


print flatten(n)

```python prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3, } stock = { "banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15, }

def compute_bill(food):
total = 0
for item in food :
if stock[item] > 0:
total += prices[item]
stock[item] -= 1
return total

对于两个key相同的dictionary,可以在同一个for循环中分别获取两个对应key的value

 posted on 2015-05-14 09:08  絮状颗粒  阅读(180)  评论(0)    收藏  举报