python学习笔记(一)

1.2 Swapping Values WithoutUsing a Temporary Variable

a, b, c = b, c, a

1.3 Constructing a Dictionary Without Excessive Quoting

data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
def makedict(**kwargs):
    return kwargs
data = makedict(red=1, green=2, blue=3)
def dodict(*args, **kwds):
    d = {}
    for k, v in args: d[k] = v
    d.update(kwds)
    return d
tada = dodict(*data.items(  ), yellow=2, green=4)
def dodict(*args, **kwds):
    d = dict(args)
    d.update(kwds)
    return d
tada = dodict(*data.items(  ), yellow=2, green=4)
mydate = sorted(mydate.items(), key=lambda mydate:mydate[1])
扩展:
def accept(**kwargs):
    for keyword, value in kwargs.items():
      #print "%s => %r" % (keyword, value)
      print "%s " % (keyword)

def multiply(*args):
    total = 1 
    for arg in args:
      total *= arg 
    return total
accept(foo='bar', spam='egg')
print multiply(2,3)
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
1.4 Getting a Value from a Dictionary
d = {'key':'value'}
if d.has_key('key'):      # or, in Python 2.2 or later: if 'key' in d:
  print d['key']
else:
  print 'not found'
print d.get('key', 'not found')

1.5 Adding an Entry to a Dictionary

theIndex = {}
def addword(word, pagenumber):
    if theIndex.has_key(word):
        theIndex[word].append(pagenumber)
    else:
        theIndex[word] = [pagenumber]
def addword(word, pagenumber):
    try: theIndex[word].append(pagenumber)
    except AttributeError: theIndex[word] = [pagenumber]
def addword(word, pagenumber):
    theIndex.setdefault(word, []).append(pagenumber)

1.6 Associating Multiple Values with Each Key in a Dictionary

d1 = {}
d1.setdefault(key, []).append(value)

d2 = {}
d2.setdefault(key, {})[value] = 1
1.7 Dispatching Using a Dictionary
#!/usr/bin/python

animals = []
number_of_felines = 0 

def deal_with_a_cat(  ):  
    global number_of_felines
    print "meow"
    animals.append('feline')
    number_of_felines += 1

def deal_with_a_dog(  ):  
    print "bark"
    animals.append('canine')

def deal_with_a_bear(  ):  
    print "watch out for the *HUG*!"
    animals.append('ursine')

tokenDict = { 
    "cat": deal_with_a_cat,
    "dog": deal_with_a_dog,
    "bear": deal_with_a_bear,
    }   

# Simulate, say, some words read from a file
words = ["cat", "bear", "cat", "dog"]

for word in words:
    # Look up the function to call for each word, then call it
    functionToCall = tokenDict[word]
    functionToCall()
    # You could also do it in one step, tokenDict[word]()

print 'number_of_felines = ', number_of_felines

Method

Description

Non-mutating methods

L.count(x)

Returns the number of occurrences of x in L

L.index(x)

Returns the index of the first occurrence of item x in L or raises an exception if L has no such item

Mutating methods

L.append(x)

Appends item x to the end of L

L.extend(l)

Appends all the items of list l to the end of L

L.insert(i,x)

Inserts item x at index i in L

L.remove(x)

Removes the first occurrence of item x from L

L.pop([i])

Returns the value of the item at index i and removes it from L; if i is omitted, removes and returns the last item

L.reverse(  )

Reverses, in-place, the items of L

L.sort([f])

Sorts, in-place, the items of L, comparing items by f; if f is omitted, cmp is used as comparison function






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值