python下条件判断

390 阅读2分钟

首先学习下一个知识:

map用法

描述

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

语法

map(function, iterable, ...)

参数

function -- 函数 iterable -- 一个或多个序列

返回值

Python 2.x 返回列表。

Python 3.x 返回迭代器。

实例

python3

def square(x):  # 计算平方数
    return x**2
    
    
print(map(square, [1, 2, 3, 4, 5]))  # 计算列表各个元素的平方
print(type(map(lambda x: x**2, [1, 2, 3, 4, 5]))) # type获取类型
# 使用 lambda 匿名函数
# 提供了两个列表,对相同位置的列表数据进行相加
print(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
m = map(lambda x: x**2, [1, 2, 3, 4, 5])
for  v in m:
    print(v)

# 输出如下    
<map object at 0x105a1f410>
<class 'map'>
<map object at 0x105a6c410>
1
4
9
16
25

python2

#coding=utf-8
def square(x):  # 计算平方数
    return x**2


print(map(square, [1, 2, 3, 4, 5]))  # 计算列表各个元素的平方
print(type(map(lambda x: x**2, [1, 2, 3, 4, 5])))
# 使用 lambda 匿名函数
# 提供了两个列表,对相同位置的列表数据进行相加
print(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
m = map(lambda x: x**2, [1, 2, 3, 4, 5])
for v in m:
    print(v)
 
 #输出如下:
[1, 4, 9, 16, 25]
<type 'list'>
[3, 7, 11, 15, 19]
1
4
9
16
25

条件筛选

L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in map(lambda x: str(x), L1)]
print(L2) #['hello', 'world', '18', 'apple', 'none']
L3 = [s.lower() for s in L1 if isinstance(s, str)]
print(L3) #['hello', 'world', 'apple'] 
L4 = [s.lower() if isinstance(s, str) else s for s in L1]
print(L4) #['hello', 'world', 18, 'apple', None]

总结

由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。

# -*- coding: UTF-8 -*-
 
num = 9
if num >= 0 and num <= 10:    # 判断值是否在0~10之间
    print 'hello'
# 输出结果: hello
 
num = 10
if num < 0 or num > 10:    # 判断值是否在小于0或大于10
    print 'hello'
else:
    print 'undefine'
# 输出结果: undefine