0
点赞
收藏
分享

微信扫一扫

条件、循环、推导

杰克逊爱学习 2022-04-06 阅读 51
python

布尔条件

用作布尔表达式时,下面的值都将被解释器视为假:False None 0 "" () [] {}

True和False不过是0和1的别名,虽然看起来不同,但作用是相同的。


比较运算符
表达式描 述
x == yx 等于y
x < yx小于y
x > yx大于y
x >= yx大于或等于y
x <= yx小于或等于y
x != yx不等于y
x is yx和y是同一个对象
x is not yx和y是不同的对象
x in yx是容器(如序列)y的成员
x not in yx不是容器(如序列)y的成员


字符串和序列的比较

print('e:{}'.format(ord('e')))
print('F:{}'.format(ord('F')))
print('f:{}'.format(ord('f')))
# output: e:101
# output: F:70
# output: f:102

print('efg' > 'fgh')
# output: False

print('efg' > 'egh')
# output: False

print('efg' > 'd')
# output: True

print('efg' > 'Fgh')
# output: True


if、else、elif


# if boolCondition:
#       action

if 2>1:
    print(True)
if 2 < 1:
    print(False)
# output: True
# if boolCondition:
#       action1
# else:
#       action2

a = 2
if a > 1:
    print('a={0}:True'.format(a))
else:
    print('a={0}:False'.format(a))
# output: a=2:True
# output: a=1:False
a = 5   # (2\4\5)
if a == 1:
    print('a={0}:action1'.format(a))
elif a == 2:
    print('a={0}:action2'.format(a))
elif a == 3:
    print('a={0}:action3'.format(a))
elif a == 4:
    print('a={0}:action4'.format(a))
else:
    print('a={0}:action5'.format(a))
# output: a=2:action2
# output: a=4:action4
# output: a=5:action5

链式比较

a = 2  # (2\5)
if 1 < a < 4:
    print('a={0}:action1'.format(a))
else:
    print('a={0}:action2'.format(a))
# output: a=2:action1
# output: a=5:action2



断言assert

在程序中添加assert语句充当检查点。

assert 语句是在程序中插入调试性断言的简便方式:

assert_stmt ::=  "assert" expression ["," expression]

简单形式 assert expression 等价于

if __debug__:
    if not expression: raise AssertionError

扩展形式 assert expression1, expression2 等价于

if __debug__:
    if not expression1: raise AssertionError(expression2)

a = -1
assert a > 0
# output: Traceback (most recent call last):
#   File "E:\PyCode\Python_Study\LsitDemo.py", line 2, in <module>
#     assert a > 0
# AssertionError
assert a > 0, 'a为负数'
# output: Traceback (most recent call last):
#   File "E:\PyCode\Python_Study\LsitDemo.py", line 7, in <module>
#     assert a > 0, 'a为负数'
# AssertionError: a为负数


While循环

# while condition:
#     action
a = 0
while a < 10:
    a += 1
print(a)
# output: 10
# while condition:
#     action with break
a = 2  # (-2,2)
while a < 10:
    if a < 0:
        print('into break')
        break
    else:
        a += 1
else:
    print('into else')
print(a)

# output: into break
# output: -2

# output: into else
# output: 10
# while condition:
#     action with continue
# else:
#     action
a = -2
while a < 10:
    if a < 0:
        a += 1
        print('into continue')
        continue
    else:
        a += 100
else:
    print('into else')
print(a)

# output: into continue
# output: into continue
# output: into else
# output: 100


For循环

只要能够使用for循环,就不要使用while循环。

for num in list(range(5)):
    print(num)
# output: 0
# output: 1
# output: 2
# output: 3
# output: 4

for num1 in list(range(5)):
    if num1 not in [x for x in list(range(1,4))]:
        print(num1)
# output: 0
# output: 4​

迭代字典

dict1 = {'name': 'python', 'vision': '310'}
for k in dict1:
    print('{0}:{1}'.format(k, dict1[k]))
# output: name:python
# output: vision:310

并行迭代

names = ['pin', 'coco', 'jeff']
heights = [148, 123, 168]
for k in range(len(names)):
    print('name:{0},height:{1}'.format(names[k], heights[k]))
# output: name:pin,height:148
# output: name:coco,height:123
# output: name:jeff,height:168

for name, height in zip(names, heights):
    print('name:{0},height:{1}'.format(name, height))
# output: name:pin,height:148
# output: name:coco,height:123
# output: name:jeff,height:168

print(list(zip(zip(names, heights))))
# output: [(('pin', 148),), (('coco', 123),), (('jeff', 168),)]
strings = 'python'
heights = [148, 123, 168]

for i, j in enumerate(strings):
    print('name:{0},height:{1}'.format(i, j))
# output: name:0,height:p
# output: name:1,height:y
# output: name:2,height:t
# output: name:3,height:h
# output: name:4,height:o
# output: name:5,height:n

顺序迭代和反向迭代

list1 = [1, 3, 2]

for i in sorted(list1):
    print(i)
# output: 1
# output: 2
# output: 3

for i in sorted(list1, reverse=True):
    print(i)
# output: 3
# output: 2
# output: 1

list2 = list('bca')
for i in sorted(list2, key=str.upper):
    print(i)
# output: a
# output: b
# output: c

推导

使用圆括号代替方括号并不能实现元组推导,而是将创建生成器。可使用花括号来执行字典推导。

print([x for x in range(10)])
# output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print([x ** 2 for x in range(10) if x < 5])
# output: [0, 1, 4, 9, 16]

print([(x, y) for x in range(0, 3) for y in range(4, 7)])
# output: [(0, 4), (0, 5), (0, 6), (1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6)]

dict1 = {'{0}:{1}'.format(i, i ** 2) for i in range(3)}
print(dict1)
# output: {'2:4', '0:0', '1:1'}

举报

相关推荐

0 条评论