Python: 学习系列之三:基础介绍二

系列

对象的布尔值

"""
    以下对象的布尔值为False, 其他的对象都为True
"""
a = bool()  # 默认值为False
a = bool(False)  #
a = bool("")  # 空字符串
a = bool(None)  #
a = bool([])  # 空列表
a = bool(())  # 空元组
a = bool({})  # 空字典
print(a)

if 18 and 'python':
    print('18 is True,"python" is True')

三目运算符

"""
    这点真难用
    Python语言不像Java、JavaScript等这些语言有类似:
    判段的条件?条件为真时的结果:条件为假时的结果
    这样的三目运算,但是Python也有自己的三目运算符:   
    条件为真时的结果 if 判段的条件 else 条件为假时的结果

"""
scoreA = 29
scoreB = 20
result = 'A大于B' if scoreA > scoreB else 'A小于B'
print(result)

# 三目运算符写法
print(x if(x>y) else y)

循环语句:只有while 和 for-in

while True:
    word = input("请输入一个单词:")
    if not word:
        break
    print('输入的单词是:', word)

# 遍历列表
for item in ['a', 'b', 'c']:
    print(item)

# 遍历列表, 这里只能打印出a, b,不能打印出c
a = ['a', 'b', 'c']
for item in a:
    if item == 'b':
        a.remove(item)
    print(item)

# 遍历列表, 这里只能打印出a, b,c
# 这里如果对列表进行修改操作,最好是先通过切片操作生成一份序列的拷贝
a = ['a', 'b', 'c']
for item in a[:]:
    if item == 'b':
        a.remove(item)
    print(item)

# 遍历列表 [(0, 'a'), (1, 'b'), (2, 'c')]
for index, item in enumerate(['a', 'b', 'c']):
    print(index, item)

# 遍历列表 [(1, 'a'), (2, 'b'), (3, 'c')]
for index, item in enumerate(['a', 'b', 'c'], 1):
    print(index, item)

# 遍历元组
for item in ('a', 'b', 'c'):
    print(item)

# 遍历字典 [('name', 'cong'), ('age', 20)]
for key, value in {'name': 'cong', 'age': 20}.items():
    print(key, value)

循环语句中的break-else

"""
    只有循环正常结束时,下面的else语句才会被执行, 如果遇到了break, else语句不会被执行
"""
for item in range(10):
    print(item)
else:
    print('所有的元素都遍历了,没有遇到break')

for item in range(10):
    if item == 8:
        break
    print(item)
else:  
    print('遇到break了,这条语句不会被执行')

 Zip方法的使用

a = ['a', 'b', 'c']
b = [1, 2, 3]
c = ['x', 'y', 'z', 'xx']  # 如果几个可迭代对象的长度不同,较长的对象会被截断,也就是说'xx'不会被用到
print(zip(a, b, c))  # <zip object at 0x000002AB25A68808>
print(list(zip(a, b, c)))  # [('a', 1, 'x'), ('b', 2, 'y'), ('c', 3, 'z')] 列表中的元素都是元组

for x, y, z in zip(a, b, c):
    print(x, y, z)

"""
    使用zip(*)对zip对象解压缩
"""
d = zip(a, b, c)

print(list(zip(*d)))  # [('a', 'b', 'c'), (1, 2, 3), ('x', 'y', 'z')]

a2, b2, c2 = zip(*Ld)
print(a2, b2, c2)  # ('a', 'b', 'c') (1, 2, 3) ('x', 'y', 'z')
print(list(a2), list(b2), list(c2))  # ['a', 'b', 'c'] [1, 2, 3] ['x', 'y', 'z']

Map and Filter

"""
    指定函数作用于指定对象的每个元素
""" 
print(list(map(str.upper, 'abc')))  # ['A', 'B', 'C']


"""
过虑功能,只返回函数为True的元素
"""
print(list(filter(str.isalpha, '123abc')))  # ['a', 'b', 'c']

列表生成式

"""
主要用于生成列表的
"""
print([x*x for x in range(1,5)])  #[1, 4, 9, 16]
print([x * x for x in range(1, 5) if not x % 2])  # [4, 16],支持if语句

# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
print([(i, j) for i in range(1, 4) for j in range(1, 4)]) #支持双重循环

# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
print([(i, j) for i in range(1, 4) for j in range(1, 4) if i != j]

matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
L = [[row[i] for row in matrix] for i in range(4)]
print(L)  # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

集合生成式

"""
    功能和列表几乎一样,只取了下面一个例子,把[]换成{}就可以了
"""
print({x*x for x in range(1, 5)})  # {16, 1, 4, 9}

字典生成式

items = ['Fruits', 'Books', 'Others']
prices = [97, 98, 99]
D = {item.upper(): price for item, price in zip(items, prices)}
print(D)  # {'FRUITS': 97, 'BOOKS': 98, 'OTHERS': 99}


items = ['Fruits', 'Books', 'Others']
prices = [97, 98, 99]
D = {item.upper(): price for item, price in zip(items, prices) if item != 'Books' and price > 98}
print(D)  # {'OTHERS': 99}

生成器

"""
    生成器是一个可迭代对象
    如下是一个生成器表达式,它是被小括号括起来的
"""
ge = (i*i for i in range(1, 5))
print(ge)  # <generator object <genexpr> at 0x000002AC76111CF0>

print(next(ge))  # 1
print(next(ge))  # 4
print(next(ge))  # 9

"""
    生成器函数,它通过关键字返回推算出的元素,生成器函数与普通函数的区别在于:当调用内置函数next()或使用for-in语句进行迭代时,
    执行完yield语句就会将生成器函数挂起,下次从挂起的地方继续执行。
"""
def fun(n):
    for i in range(n):
        yield i


f = fun(3)
print(f)  # <generator object fun at 0x00000264954870C0>
print(type(f)) #<class 'generator'>
print(next(f))  # 0
print(next(f))  # 1
print(next(f))  # 2
print(next(f))  # raise StopIteration

迭代器

"""
    1. 只有zip才是一个迭代器,列表和元组都不是,迭代器只能遍历一次,遍历后迭代器就空了,取不出来任何东西
    2. 可以用于for-in语句的对象被称为可迭代(Iterable)对象,使用range,list,tuple,string,dict,set,生成器(generator),可以调于ininstance()判断它是列是一个可迭代对象。
    3. 如果一个可迭代对象可被next()调用,那么它可以称为迭代器(Iterator),列表和元组都不是,可以调用内置函数iter()将其转化为迭代器。
    4. 一个对象实现了特殊方法__iter__()和__next__()后,那这个对象就是一个迭代器,也是一个可迭代对象。
"""

x = [1, 2]
# print(next(x))  # TypeError: 'list' object is not an iterator
y = (1, 2)
# print(next(y))  # TypeError: 'tuple' object is not an iterator

print(next(iter(x))) #1,可以转化为一个可迭代对象

x = ["a", "1"]
y = ["b", "2"]
z = zip(x, y)

print(next(z))  # ('a', 'b')
print(next(z))  # ('1', '2')
# print(next(z))  # Error: print(next(z)) StopIteration
print(list(z))  # [] , 空的

函数

"""
    1. 下面是定义函数,a,b是形式参数(形参),c是实际参数(实参)
    2. 函数创建后,就创建了一个函数对象,类型是function
    3. 传一个可变类型参数时,
"""
def add(a, b):
    return a+b
c = 2
print(add(1, c))  # 3
print(add)  # <function add at 0x00000248889EC268>



"""
    1. 函数注解
    2. 解释器会忽略函数注解,解释器并不会使用函数注解来检查实参的类型和返回值
"""

def test(a: list, b: int) -> 'it return a string':
    return a + str(b)

def test2(a: str, b: int) -> list:
    return a+b

print(test('1', 2))  # 12
print(test2(1, 2))  # 3
# {'a': <class 'list'>, 'b': <class 'int'>, 'return': 'it return a string'}
print(test.__annotations__)
print(help(test))


"""
    传一个可变类型参数时,实际上实参会被修改,如下b就修改,如果不想修改b,那可以传它的拷贝
"""
def push(a):
    a.append("aaa")
b = []
push(b)
print(b)  # ['aaa']


"""
    pass语句什么都不做,它就是一个占位符,一般用在if语句,for-in语句,定义函数的函数体, 类似于todo
"""
def test():
    pass

test() # 啥也不做,通常用于还没想好方法怎么写时,为了让程序正常运行,先写了pass作为占位符




"""
    带默认值实参
"""
def test(a=5):
    return print(a)

test()  # 5
test(8)  # 8


"""
    函数返回多值是返回一个元素
"""
def max_and_min_value():
    return 1, 100


print(max_and_min_value())  # (1, 100),返回得是一个元组


"""
    位置形参与关键字形参
"""
def subtract(a, b):
    return a-b
print(subtract(2, 1))  # 这是位置形参
print(subtract(a=3, b=1))  # 这是关键字形参


"""
    使用*定义关键字形参
"""
def divide(a, b, *, c, d):
    return print(a, b, c, d)


# TypeError: divide() takes 2 positional arguments but 4 were given
# divide(1, 2, 3, 4)

divide(1, 2, c=3, d=4)  # 1 2 3 4


"""
    使用*定义可变关键字形参
"""
def test(*a):
    print(a)

test(1, 2)  # (1, 2)


"""
    使用*将序列中的每一个元素转换为位置实参
"""
def test(a, b, c):
    print(a, b, c)


L = [1, 2, 3]
L = (1, 2, 3)
test(*L)  # 1 2 3


"""
    1. 使用两个*定义个数可变的关键字形参
    2. 定义函数时,位置形参必须在关键字形参之前
"""
def test(**kwargs):
    print(kwargs)

test()  # {}
test(a=1, b=2)  # {'a': 1, 'b': 2}
L=['Python','Java','Swift']
print(sorted(L, key=len, reverse=True))  # ['Python', 'Swift', 'Java']

"""
    使用两个*将序列中的每一个元素转换为关键字实参
"""
def test(a, b, c):
    return print(a, b, c)
def test2(**kwargs):
    print(kwargs)

test(1, 2, 3)  # 1 2 3
test(a=1, b=2, c=3)  # 1 2 3
d = {'a': 1, 'b': 2, 'c': 3}
test(**d)  # 1 2 3
test2(**d)  # {'a': 1, 'b': 2, 'c': 3}

文档字符串

def test():
    """This is a test document string.

    This is the detailed information
    """
    pass


print(test.__doc__)  # This is a test document string.

# Help on function test in module __main__:
# test()
# This is a test document string
# None
print(help(test))

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值