Scratch and Python 2018 Summer - Python Lecture 3
交大公開課
來源:https://hackmd.io/5oUx5oXUSEGuCrZG1Pm4kQ?both
===
Iterables: bags of items
list
tuple
str
generator
range
range(n)
sample code
range(L,U)
sample code
range(L,U,step)
sample code
Iterator: an access to a certain item and the iterator to its next item
it = iter(iterables)
next(it)
or it.__next__()
StopIteration
will be raised if no more elements.next(it,default)
gives default
if no more elements, otherwise the next element will be given.except Type:
to catch certain kind of error or exceptionType
pass
to do nothing.in
operator
Some useful tools
List comprehension
type(int(10*x**0.5) for x in range(0,100,5) if x % 2 == 0)
[int(10*x**0.5) for x in range(0,100,5) if x % 2 == 0]
More tools
'''
chr
chr(65)
ord
ord('A')
str
's of length 1 to represent characters.print('123'[0])
print('123'[-1])
index()
print('123123123'.index('312'))
print('abcde'[2:])
print('abcde'[:2])
print('abcde'[1:3])
in
and not in
print('abc' in 'zabcy')
print('gg' not in 'zabcy')
upper()
and lower()
isupper()
, islower()
, isdecimal()
, isalpha()
, isalnum()
'123.0'.isdecimal()
join(list_str)
', '.join([str(i) for i in range(10)])
split(string)
'<a href="https://automatetheboringstuff.com/">'.split('"')
startswith(string)
and endswith(string)
http
and end with html
strip()
, rstrip()
, lstrip()
.format()
: Replace placeholder {}
with corresponding variables.
'Case {}: {}, {}'.format(1,68.7,'passed')
https://en.wikipedia.org/w/api.php?action=rsd
//en.wikipedia.org/w/api.php?action=rsd
/w/api.php?action=rsd
api.php?action=rsd
import random
a
to b
: random.randint(a,b)
[0.0,1.0)
: random.random()
lst
: random.shuffle(lst)
random.choice(seq)
k
samples from a population: random.sample(population,k)
0
to 9
0
to 9
with hints
Write a program to helps you play Bulls and Cows.
There are many approaches to help you to play the game. But the following strategy will help you to guess the number within 10 steps.
Maintain a list of candidates.
Randomly pick a candidate from the list, and guess it.
If the answer is what you guess, then you win. Otherwise, you would know how many bulls and cows.
Remove the candidates which do not match the result from the list. Go to step 2.
Unfinished sample code
list
and tuple
[]
[12, 3.4, None, True, 'string', print]
i
-th element of list x
: x[i]
[123,456][1]
[12, 3.4, None, True, 'string', print][5]('hello world')
[123,456][1.0]
()
(element,)
type(('str'))
and type(('str',))
type((x for x in range(5)))
tuple(x for x in range(5))
to generate (0,1,2,3,4)
(12, 3.4, None, True, 'string', print)
list()
and tuple()
list(('a','b','c'))
tuple(['d','e','f'])
list('hello')
tuple('hello')
a_list_or_tuple[-1]
print(['a','b','c','d','4'][1:3])
print(['a','b','c','d','4'][2:])
print(['a','b','c','d','4'][:4])
print(['a','b','c','d','4'][-3:])
print(['a','b','c','d','4'][:-3])
print(['a','b','c','d','4'][3:1])
print(['a','b','c','d','4'][1:5:3])
in
not in
+
*
index()
print([0,1,2,0].index(0))
insert(pos,val)
: insert val
to position pos
a = [0,1,2]
. What will happen if we perform a.insert(1,3)
?append(val)
pop()
: remove the last element and return its valuepop(pos)
: remove the element of position pos
remove(val)
: remove an element of value val
a = [1,0,0,1]
. What will happen if we perform a.remove(1)
?sort()
: sort the list ascendinglytype(value)
and id(name)
import copy
copy.copy()
: Shallow copycopy.deepcopy()
: Deep copy[[0]*5,[0]*5,[0]*5,[0]*5,[0]*5]
[[0]*5] * 5
[[0]*5 for _ in range(5)]
dict
list
is indexed by int
0
to len()-1
instructor = {'Name': 'MZ', 'Height': 178, 'Weight': 108}
print(instructor['Name'])
print(instructor['age'])
{}
dict
is mutable
a_dict[key]=val
a_dict[key]=val
del
del a_dict[key]
del
can also undefine a variable.keys()
values()
items()
in
print('MZ' in instructor)
print('Name' in instructor)
print(('Name','MZ') in instructor)
get(key,val)
: If key
is missing, then return val
setdefault(key,val)
: if there is no such key
, initialize the key-value pair to (key,val)
and return val
. Otherwise return the value corresponding key
.