Python的单语句块、列表解析、字典解析、断言解析

开课吧开课吧锤锤2021-03-19 15:42

    从Python20世纪90年代诞生至今,广泛被应用于各个领域,其强大而丰富的库是Python的一大特点,其次就是对C类语言的粘合性强,这使得Python在数据处理方面能够得心应手,所以到今天就有许许多多的从业人员纷纷学习Python语言。

PY

    单语句块

if True:
    print('yes')if True: print('yes')

x = 5y = 3if x > y:
    print(y)else:
    print(x)#-------------print((y if y < x else x))
print(x)
yes
yes
3
3
5

    列表解析

    生成新列表的简化的for循环

aList = [1, 2, 3, 4, 5]
bList = []for i in aList:
    bList.append(i * 2)#-----------------------------------#nameL = [line.strip() for line in open(file)]bList = [i * 2 for i in aList]
print(bList)
[2, 4, 6, 8, 10]
print("列表解析可以做判断的")
aList = [1, 2, 3, 4, 5]
bList = [i * 2 for i in aList if i % 2 != 0]
print(bList)
列表综合可以做判断的
[2, 6, 10]
print("列表解析也可以嵌套的")
aList = [1, 2, 3, 4, 5]
bList = [5, 4, 3, 2, 1]
bList = [i * j for i in aList for j in bList]# for i in aList:#    for j in bList:#        print i * jprint(bList)
列表综合也可以嵌套的
[5, 4, 3, 2, 1, 10, 8, 6, 4, 2, 15, 12, 9, 6, 3, 20, 16, 12, 8, 4, 25, 20, 15, 10, 5]

    字典解析

aList = ['a', 'b', 'a', 'c']
aDict = {i:aList.count(i) for i in aList}
aDict
{'a': 2, 'b': 1, 'c': 1}
bDict = {i:j*2 for i,j in aDict.items()}
bDict
{'a': 4, 'b': 2, 'c': 2}

    断言

    设定运行过程中必须满足的条件,当情况超出预期时报错。常用于文件读入或格式判断时,有助于预防异常的读入或操作。

a = 1b = 2assert a == b, "a is %s, b is %s" % (a, b)if a == b:    passelse:
    print("a is %s, b is %s" % (a, b))
---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

 in ()
      1 a = 1
      2 b = 2
----> 3 assert a == b, "a is %s, b is %s" % (a, b)
      4 
      5 if a == b:

AssertionError: a is 1, b is 2

    以上就是单语句块、列表解析、字典解析、断言的全部内容,更多Python教程相关内容尽在开课吧广场Python教程频道。

有用
分享