基础语法

字符串 str

a = 'abc123'
b = 'xyz789'

# 字符串中是否包含 True
print('a' in a)

# 字符串拼接 abc123xyz789
print(a + b)

# 使用 % 来格式化,%% 表示输出 % 本身
# %d-整数  %f-浮点数  %s-字符串  %x-十六进制整数
'Hello, %s' % 'world'

# 使用 format() 函数
'Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)

# 使用 f-string 格式
r = 2.5
s = 3.14 * r ** 2
print(f'The area of a circle with radius {r} is {s:.2f}')

# 字符串重复叠加N次 abc123abc123abc123
print(a * 3)

# 字符串切片 ab
print(a[0:2])

有序列表 list


# 定义列表
testList = ['hello', 'world']

# 列表第0个元素
testList[0]

# 赋值或替换
testList[1] = 'test'

# 获取最后一个元素 可以直接用负号 testList[-1]
testList[len(testList) -1]

# 插入到末尾
testList.append('末尾添加')

# 插入到指定索引位置
testList.insert('插入到指定索引位置', 1)

# 末尾移除
testList.pop()

# 移除指定索引位置
testList.pop(1)

# 合并,跟PHP的array_merge()类型
testList.extend(['hello', 'python'])

# 也可以直接使用"+",建议使用extend,因为使用"+"会额外创建一个新列表
testList = testList + ['hello', 'python']

# 可以混合类型
testList = ['hello', True, 13, ['嵌套', '也行']]

# 倒序
testList[::-1]

# 倒序,返回的是迭代器对象
reversed(testList)

元组 tuple

一些只读的场景,可以使用 tuple 来代替 list


# 多元素
testTuple = ('a','b')

# 空tuple
testTuple = ()

# 单元素,增加 "," 防止歧义
testTuple = (1,)

# 混合 其中的 list 的值是可变的,不变的只是 tuple 指向 list 的指针
testTuple = ("a","b",["c","d"])

# 元组拆包(将元组元素分别赋值给变量)
a,b,cd = testTuple

# *variable用于在函数调用时获取任意长度的位置
# 这里的*_用于接收除了第0个和第1个元素以外的所有元素(通常是不需要用到的元素)
element_1, element_2, *_ = testTuple

字典 dict


# 定义字典
testMap = {'zhangsan': 99, 'kk': 0}

# 赋值字典
testMap['kk'] = 13

# 赋值字典设置默认值
testMap.setdefault("arr", []).append("item1")

# key是否存在
if 'kk' in testMap:

# 获取kk的值
testMap['kk']
testMap.get('kk', '可指定默认值')

# 删除某个key
del testMap['kk']
testMap.pop('kk')

# 合并字典
a = {"k":"v"}
b = {"key":"value"}
a.update(b)
print(a)

# 可以接受二元组 {'a': 'b', 'c': 'd'}
print(dict((('a', 'b'), ('c', 'd'))))

默认值字典

collections.defaultdict是Python中的一个容器类型,它继承自字典(dict)。与普通字典不同的是,当访问一个不存在的键时,defaultdict会自动为该键生成一个默认值,而不是抛出KeyError异常

from collections import defaultdict

class Node:
    __slots__ = ("name")

def default_node(name='张三'):
    n = Node()
    n.name = name
    return n

d = defaultdict(int)
print(d["apple"])  # 输出:0
d = defaultdict(str)
print(d["banana"])  # 输出:""
d = defaultdict(default_node)
print(d["class"])  # 输出:Node

collections.Counter用于计算可哈希对象的数量,它继承自字典(dict),其中元素作为key,元素的计数作为value

from collections import Counter

# 创建一个列表
list1 = ['a', 'b', 'c', 'a', 'b', 'b']

# 使用Counter计算列表中每个元素的数量
counter = Counter(list1)

# 输出结果 Counter({'b': 3, 'a': 2, 'c': 1})
print(counter)

无序集合 set


# 输出结果会去重
testList = [1, 1, 2, 2, 3, 3]
a = set(testList)

# 重复值添加无效,不重复值可添加
a.add(1)
a.add(999)

# 移除元素
a.remove(999)

# 清空集合
a.clear()

# 移除任意元素
a.pop()

b = {6, 7, 8, 11, 11}
# 并集
a.union(b)
a | b

# 将a的内容设置为a和b的并集
a.update(b)
a |= b

# 交集
a.intersection(b)
a & b

# 将a的内容设置为a和b的交集
a.intersection_update(b)
a &= b

# 差集(a有b没有)
a.difference(b)
a - b

# 将a的内容设置为a和b的差集
a.difference_update(b)
a -= b

# 双向差集(a有b没有以及b有a没有)
a.symmetric_difference(b)
a ^ b

# 将a的内容设置为a和b的双向差集
a.symmetric_difference_update(b)
a ^= b

# a是否是b的子集
a.issubset(b)

# a是否是b的超集
a.issuperset(b)

# a、b没有交集
a.isdisjoint(b)

zip函数

# 打包函数,将列表、元组或其他序列元素配对
a = ['a', 'b', 'c']
b = ['x', 'y', 'z']
print(list(zip(a, b)))  # [('a', 'x'), ('b', 'y'), ('c', 'z')]
print(dict(zip(a, b)))  # {'a': 'x', 'b': 'y', 'c': 'z'}

c = ['1', '2', '3']
print(list(zip(a, b, c)))  # [('a', 'x', '1'), ('b', 'y', '2'), ('c', 'z', '3')]
print(dict(zip(a, b, c)))  # 报错

条件判断

注意:不需要括号,冒号和缩减是必须的,否则逻辑可能会出现异常

a = 4

if a == 3:
    print('a')
    print('3')
elif a == 4:
    print('b')
    print(4)
else:
    print('c')
    print(5)

循环

和其它编程语言一样,中断循环可使用 break continue 关键字

使用 for in 遍历


testList = ['k', 'k', 's', 'b']

for item in testList:
    print(item)

使用 while 循环

a = 10
while a > 0:
    print(a)
    a = a - 1

Python没有其它语言那种 for(int i =0;i<10;i++) 可以借助 range() 函数来模拟

for i in range(0, 10):
    print(i)

遍历字典

testDict = {'a': 'a1', 'b': 'b1'}

for k, v in testDict.items():
    print(k, '=>', v)

key value 都要

testList = [11, 22, 33, 44, 55]

for k, v in enumerate(testList):
    print(k, "=>", v)

多维遍历


testList = [('a', 'b', 'c'), ('x', 'y', 'z')]

for item1, item2, item3 in testList:
    print(item1)
    print(item2)
    print(item3)
    print('-' * 100)

pass关键字

def todo():
    pass

if 2 > 1:
    pass

切片 slice


testList = ['a', 'b', 'c', 'd']
print(testList[0:3])                # 从索引0取到索引3 [0,3)
print(testList[:3])                 # 0可以不填
print(testList[1:3])                # [1,3)
print(testList[-2])                 # c,倒数第2个
print(testList[-2:])                # [c,d],倒数第2个截取到最后
print(testList[0:4:2])              # 索引0-3,每2个取1个
print(testList[::3])                # 所有数,每3个取1个
print(testList[:])                  # 原样复制一个list

# 这种方式会创建一个新的列表,包含原列表中每隔一个元素,然后将新列表赋值给变量testList。原列表testList的引用会被丢弃,新列表成为新的testList
testList = testList[::2] 

# 原地操作,比赋值给变量更省内存
testList[:] = testList[::2]

列表生成式

for 前面必须加 else,for 后面不能加 else

print(list(range(1, 11)))
print([x * x for x in range(1, 11)])
print([x * x for x in range(1, 11) if x % 2 == 0])
print([x + y for x in ['a', 'b', 'c'] for y in ['x', 'y', 'z']])

生成器 generator

将列表生成式的 [] 换成 () 就会返回一个生成器

g = (x * x for x in range(1,11))

for x in g:
    print(x)

使用 yield 关键字

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1

    return True

# 使用 for 迭代生成器
for x in fib(10):
    print(x)

# 使用 next() 方法,返回值可以通过 StopIteration 捕获
g = fib(10)
while True:
    try:
        print(next(g))
    except StopIteration as e:
        print(e.value)
        break

类型判断

a = 1
# a是否是int
print(isinstance(a, int))
# a是否是int或float
print(isinstance(a, (int, float)))

迭代器

  • Iterator 对象表示一个数据流,可以被 next() 函数调用,直到没有数据抛出 StopIteration
  • Iterator 对象是惰性的,只有需要返回下一个数据时才会计算,所以它可以放无限大的数据
  • Iterable 是可迭代的,但是它不能被 next() 函数调用,它存放数据的大小受内存限制
  • iter()方法可以将 Iterable 转换为 Iterator 如:iter([1,2,3,4])
from collections.abc import Iterator
from collections.abc import Iterable

testList = [1, 2, 3]
print(isinstance(testList, Iterable))       # True
print(isinstance(testList, Iterator))       # False
testList = iter(testList)
print(isinstance(testList, Iterable))       # True
print(isinstance(testList, Iterator))       # True

results matching ""

    No results matching ""