python编程快速上手----繁琐工作自动化(代码)

应该会是第一本正经看完的书,代码怕丢,记录一下

4.10.1

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
spam = ['apples','bananas','tofu','cats']

def douhao(lianbiao):
    lianbiao[-1] = 'and ' + lianbiao[-1]
    return lianbiao

print(str(douhao(spam)))

#print(douhao(spam),sep = ',')

4.10.2

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
grid = [['.','.','.','.','.','.'],
        ['.','o','o','.','.','.'],
        ['o','o','o','o','.','.'],
        ['o','o','o','o','o','.'],
        ['.','o','o','o','o','o'],
        ['o','o','o','o','o','.'],
        ['o','o','o','o','.','.'],
        ['.','o','o','.','.','.'],
        ['.','.','.','.','.','.']]
print(len(grid))
'''
#output grid
for i in range(len(grid)):
        j = 0
        for j in range(len(grid[i])):
                print(grid[i][j],end='')
        print(' ')
'''

#the right answer
for i in range(6):
        j = 0
        for j in range(9):
                print(grid[j][i],end='')
        print(' ')

5.6.1

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
import pprint

stuff = {'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}

def displatInventory(inventory):
    print('inventory:')
    item_total = 0
    for i,j in inventory.items():
        pprint.pprint(str(j) + ' ' + i)
        item_total += j
    print('Total number of items:' + str(item_total))

displatInventory(stuff)

5.6.2

#!/usr/bin/env python
# -*- coding:utf-8 -*-

def displatInventory(inventory):
    print('inventory:')
    item_total = 0
    for i,j in inventory.items():
        print(str(j) + ' ' + i)
        item_total += j
    print('Total number of items:' + str(item_total))

def addToInventory(inventory,addedItems):
    for i in addedItems:
        number = 1
        #for k,v in inventory.items():
        inventory[i] = inventory.setdefault(i,0)
        inventory[i] += 1
    return inventory

inv = {'gold coin':42,'rope':1}
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
inv = addToInventory(inv,dragonLoot)
displatInventory(inv)

你可能感兴趣的:(Python)