Python 之道

Python 3 学习笔记之——基础语法

2018-10-24  本文已影响1人  seniusen
1. a, b = a, a + b
2. 条件控制和循环语句
if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3
while condition:
    statement_block
else:  # 可有可无
    statement_block
for <variable> in <sequence>:
    <statements>
else:
    <statements>
>>> a = list(range(3))
>>> a
[0, 1, 2]
>>> a = list(range(1, 5, 2))
>>> a
[1, 3]
3. 迭代器和生成器
>>> a = [1, 2, 3, 4]
>>> it = iter(a)
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
4
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

>>> it = iter(a)
>>> for i in it:
...     print(i)
... 
1
2
3
4
>>>
class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self
 
    def __next__(self):
        if self.a <= 5:
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration


myclass = MyNumbers()
myiter = iter(myclass)

for i in range(5):
    print(next(myiter))

for x in myiter:
    print(x)

>>>
1
2
3
4
5
import sys


def fibonacci(n):  # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if counter > n:
            return
        yield a
        a, b = b, a + b
        counter += 1


f = fibonacci(10)  # f 是一个迭代器,由生成器返回生成

while True:
    try:
        print(next(f), end=" ")
    except StopIteration:
        sys.exit()

>>> 0 1 1 2 3 5 8 13 21 34 55 
4. 函数
def function_name(args1, args2):
    statement
    return
5. 列表推导式
vec = [2, 4, 6]
[3 * x for x in vec if x > 3] 
>>>
[12, 18]

matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ]
[[row[i] for row in matrix] for i in range(4)]
>>>
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
6. 遍历技巧
a = [2, 4, 6]
for i, v in enumerate(a):
    print(i, v)
>>>
0 2
1 4
2 6

>>> b = ['sen', 'ius', 'en']
>>> for i, j in zip(a, b):
...     print(i, j)
... 
2 sen
4 ius
6 en

>>> for i in reversed(a):
...     print(i)
... 
6
4
2
>>> for i in sorted(b):
...     print(i)
... 
en
ius
sen
>>> 

参考资料 菜鸟教程

获取更多精彩,请关注「seniusen」!


上一篇下一篇

猜你喜欢

热点阅读