python全栈闯关--XX-细节总结汇总

1、The start value of slice is less than then end value,and the step is negative

print("if the start value less then the end value and the step is negative ! "
      "No error will be reported and empty will be returned, ")
for i in range(0, 10, -1):
    print(i)

2、One line of code exchanges the value of a and b

# One line of code exchanges value of a and b
a = 1
b = 2
a, b = b, a
print(a, b)

3、使用集合去重

li = [1, 2, 33, 33, 2, 1, 4, 5, 6, 6]
se = set(li)
print(se, type(se))
li = list(se)
print(li, type(li))

4、生成器一次性取值

def demo():
    for i in range(4):
        yield i

g = demo()
g1 = (i for i in g)
g2 = (i for i in g1)

# print(list(g))
print(list(g1))
print(list(g2))

在list(g1)中,g1跟生成器g中取值,g中值就已经取完了。因此,list(g2)时,得到得是空的列表

g、g1、g2第一个执行的,都能获取到值;如果不是第一个执行取值的,将获取到空值

懒得性原则:list(g1)调用前,没有执行代码

一次性原则:第一次取值,取完后,后续再往生成器中取值,将没值可取

5、带for循环的生成器

def add(n,i):
    return n + i

def test():
    for i in range(4):
        yield i

g = test()

for n in [1,10]:
    g = (add(n,i) for i in g)

# n = 1
# g = (add(n,i) for i in g)
#
# n = 10
# g = (add(n,i) for i in (add(n,i) for i in g))

print(list(g))

在调用list(g)前,生成器并为执行。

n=1时的表达式,带入到n=10的g中。此时,才传入变量n的值,进行代码的执行,所以最终的结果是[20, 21, 22, 23]

原文地址:https://www.cnblogs.com/zxw-xxcsl/p/11479201.html