python的高级特性

2017-11-04  本文已影响0人  抽象语法树

切片

lit = ['jack','cat',8,'tom'];
x=lit[0:3];
y=lit[-2:-1]
z=lit[:]
print(x);
print(y);
print(z);

输出:

======================= RESTART: D:/pythonTest/def.py =======================
['jack', 'cat', 8]
[8]
['jack', 'cat', 8, 'tom']
str="i love u";
print(str[2:6]);
======================= RESTART: D:/pythonTest/def.py =======================
love
L=list(range(100));
#前十个数,隔2取1
print(L[:10:2]);
#所以数,隔5取1
print(L[::5])
======================= RESTART: D:/pythonTest/def.py =======================
[0, 2, 4, 6, 8]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

迭代(Iteration)

L = ['a', 'b', 'c']
T = ('a', 'b', 'c')
D = {1: 'a', 2: 'b', 3: 'c'}
S = "i love u"
for l in L:
    print(l, end='')

print()

for t in T:
    print(t, end='')

print()

#迭代键
for key in D:
    print(key, end='')

print()

#迭代值
for value in D.values():
    print(value, end='')

print()

#迭代键和值
for k, v in D.items():
    print("%d" % k + ":" + v)

for s in S:
    print(s, end="")

输出:

abc
abc
123
abc
1:a
2:b
3:c
i love u
import collections
print(isinstance('abc', collections .Iterable))
print(isinstance(['a', 'b', 'c'], collections .Iterable))
print(isinstance(range(100), collections .Iterable))
================================================
True
True
True
for i, value in enumerate(['A', 'B', 'C']):
    print(i, value)
===========================
0 A
1 B
2 C

列表生成器

L = [x * x for x in range(1, 11)]
print(L)
=================================
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方

L = [x * x for x in range(1, 11) if x % 2 == 0]
print(L)
================================
[4, 16, 36, 64, 100]

还可以使用两层循环,可以生成全排列:

S = [ m + n for m in "AB" for n in "CD"]
print(S)
================================
['AC', 'AD', 'BC', 'BD']

列表生成式使用两个变量来生成list:

D = {"x": "A", "Y": "B", "Z": "C"}
P = [k + "=" + z for k, z in D.items()]
print(P)
=================================
['x=A', 'Y=B', 'Z=C']

生成器(generator)

g = (x * x for x in range(10))
for v in g :
    print(v)
==================================
0
1
4
9
16
25
36
49
64
81
def fun ():
    print("step 1")
    yield 1
    print("step 2")
    yield 2
    print("step 3")
    yield 3

f = fun()
next(f)
next(f)
next(f)
========================
step 1
step 2
step 3
f = fun()
while True:
    try:
        print(next(f))
    except StopIteration as e:
        print("generator end")
        break
==========================
step 1
1
step 2
2
step 3
3
generator end

迭代器

>>> from collections import Iterable
>>> isinstance([], Iterable)
True
>>> isinstance({}, Iterable)
True
>>> isinstance('abc', Iterable)
True
>>> isinstance((x for x in range(10)), Iterable)
True
>>> isinstance(100, Iterable)
False
>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
True
>>> isinstance([], Iterator)
False
>>> isinstance({}, Iterator)
False
>>> isinstance('abc', Iterator)
False

生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。

>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True

总结

上一篇下一篇

猜你喜欢

热点阅读