1.2 Swapping Values WithoutUsing a Temporary Variable
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
|
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 |