Comprehensions
count=[ ]
count.append(1)
count.append(2)
count.append(3)
count.append(4)
>>> count
[1, 2, 3, 4]
count=[]
for cou in range(1,6):
count.append(cou)
>>> count
[1, 2, 3, 4, 5]
count=list(range(1,6))
>>> count
[1, 2, 3, 4, 5]
>>>
</pre><span style="font-size:18px"></span><p></p><p></p><p><span style="font-size:18px">List语句在python中定义了一种数据结构</span></p><p></p><pre class="html" name="code">count_list=[count for count in range(1,6)]
>>> count_list
[1, 2, 3, 4, 5]
</pre><pre class="html" name="code">找出0-100之间所有的奇数
a_list=[n for n in range(1,100) if n%2==1]
a_list
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
---------------------------------------------------------------------------------------------------------------------------------------------------------
a_list=[]
for n in range(1,100):
if n%2==1:
a_list.append(n)
>>> a_list
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
>>>
按照老方法打印出行列组合
rows=range(1,10)
cols=range(1,3)
for row in rows:
for col in cols:
print(row,col)
>>>
1 1
1 2
2 1
2 2
3 1
3 2
rows=range(1,4)
cols=range(1,3)
cells=[(row,col) for row in rows for col in cols]
for cell in cells:
print(cell)
>>>
(1, 1)
(1, 2)
(2, 1)
(2, 2)
(3, 1)
(3, 2)
去除( )
for row,col in cells:
print(row,col)
word='asdsfdhfghfgjghjh'
string_counts={string:word.count(string)for string in set(word)}
>>> string_counts
{'j': 2, 's': 2, 'a': 1, 'g': 3, 'f': 3, 'd': 2, 'h': 4}
Generator Comprehensions
number_thing = (number for number in range(1, 6))
<pre name="code" class="python">>>> type(number_thing)
<class 'generator'>
</pre><pre class="python" name="code">
FUNCTION:将python小的片段粘合起来
<span style="font-size:18px;"><strong>function基本的组成是: define it</strong></span>
<span style="font-size:18px;"><strong><span style="white-space:pre"> </span>call it</strong></span>
<span style="font-size:18px;"><strong></strong></span><pre name="code" class="python">def give_money():
print('no money')
>>> give_money()
no money
>>>
<span style="font-size:18px;"><strong>
</strong></span>
def a():
return True
if a():
print("splen!")
else:
print("That was unexpected!")
>>>
splen!
</pre><pre>
Positional Arguments
def menu(wine,entree,dessert):
return{'wine':wine,'entree':entree,'dessert':dessert}
>>> menu('chardona','chicken','cake')
{'entree': 'chicken', 'wine': 'chardona', 'dessert': 'cake'}
当menu里面参数的位置不正确时,显示出的内容也不正确
def menu(person,money,thing):
return{'person':person,'money':money,'thing':thing}
>>> menu('34000','xiaot','bus')
{'person': '34000', 'money': 'xiaot', 'thing': 'bus'}