python基础语法4

python基础语法4

了解整体内容可以从基础语法1开始。本篇主要内容:列表、集合、字典、循环。

  1. list操作
def list_handle():
    list=[]
    extlist=[3,4]
    list.append(2) # 在列表末尾添加一个元素
    list.extend(extlist) # 用可迭代对象的元素扩展列表
    list.insert(0,1) # 在指定位置插入元素,第一个参数是插入元素的索引

    print(list.index(2)) # 返回列表中第一个值为 x 的元素的零基索引
    print(list.count(1)) # 返回列表中元素 x 出现的次数

    list.sort() # 排序列表中的元素
    print(list)
    list.reverse() # 翻转列表中的元素
    copylist=list.copy() # 返回列表的浅拷贝
    print(copylist)

    list.remove(1) # 从列表中删除第一个值为匹配到的元素
    newlist=list.pop(2) # 移除列表索引位置的条目,并返回该条目。 如果未指定索引号,则移除并返回列表中的最后一个条目。
    print(newlist)
    list.clear() # 删除列表里的所有元素
    print(list)
打印效果:
1
1
[1, 2, 3, 4]
[4, 3, 2, 1]
2
[]
  1. 列表实现堆栈(先进后出)
def list_stack():
    stack = [3, 4, 5]
    stack.append(6)
    stack.append(7)
    print(stack)
    stack.pop()
    print(stack)
打印效果:
[3, 4, 5, 6, 7]
[3, 4, 5, 6]
  1. 列表实现队列(先进先出)
from collections import deque
def list_queue():
    queue = deque([1, 2, 3])
    queue.append(4)
    queue.append(5)
    queue.popleft()
    print(queue)
打印效果:
deque([2, 3, 4, 5])
  1. 列表推导式
from math import pi
def list_squares():
    #平方
    print([x ** 2 for x in range(10)])

    #第一层循环x,第二层循环y,第三层判断x!=y,满足条件追加到列表中
    print([(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y])

    #复杂的表达式
    print([str(round(pi, i)) for i in range(1, 6)])

    #嵌套,matrix是3*4矩阵,
    matrix = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
    ]
    print([[row[i] for row in matrix] for i in range(4)])
    #也可以内置函数zip
    print(list(zip(*matrix)))
打印效果:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
  1. 集合,集合是由不重复元素组成的无序容器。
def set_basket():
    basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
    print(basket)
    print('orange' in basket)
    a = set('abracadabra')
    b = set('alacazam')
    #a-b是在a里不在b里;a|b取并集;a&b取交集;a^b交集以外的a或b
    print(a-b)
打印效果:
{'orange', 'apple', 'banana', 'pear'}
True
{'d', 'r', 'b'}
  1. 字典-键值对
def dict_dict():
    dict1={'name':'名字1','tel':'12332112123'}
    dict1['address']='where1'
    print(dict1)
    #dict() 构造函数创建字典
    print(dict([('name', '名字2'), ('tel', '12332112123'), ('address', 'where2')]))
    print(dict(name='名字3', tel='12332112123', address='where2'))
    #推导创建字典
    print({x: x**2 for x in (2, 4, 6)})
打印效果:
{'name': '名字1', 'tel': '12332112123', 'address': 'where1'}
{'name': '名字2', 'tel': '12332112123', 'address': 'where2'}
{'name': '名字3', 'tel': '12332112123', 'address': 'where3'}
{2: 4, 4: 16, 6: 36}
  1. 循环
def for_list():
    #循环字典,items()方法同时提取键及其对应的值
    dicttt=dict(name='名字3', tel='12332112123', address='where3')
    for k, v in dicttt.items():
        print(k, v)

    #循环序列, enumerate() 函数可以同时取出位置索引和对应的值
    for i, v in enumerate([1, 2, 3]):
        print(i, v)

    #同时循环两个或多个序列时,用 zip()函数可以将其内的元素一一匹配
    questions = ['name', 'quest', 'favorite color']
    answers = ['lancelot', 'the holy grail', 'blue']
    for q, a in zip(questions, answers):
        print('What is your {0}?  It is {1}.'.format(q, a))

    #逆向对序列进行循环,调用 reversed() 函数
    for i in reversed(range(1, 10, 2)):
        print(i)

    #指定顺序循环序列,用 sorted() 函数
    fruits = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
    for i in sorted(fruits):
        print(i)
    #去重用set()
    for f in sorted(set(fruits)):
        print(f)
打印效果:
name 名字3
tel 12332112123
address where3
0 1
1 2
2 3
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.
9
7
5
3
1
apple
apple
banana
orange
orange
pear
apple
banana
orange
pear
  1. 比较运算符
    in存在,not int不存在
    <、>、==,链式操作:a < b == c 代表a<b且b等于c
    and,or

虽然一枚小小码农,不过也在向阳努力着,本人在同步做读书故事的公众号,欢迎大家关注【彩辰故事】,谢谢支持!~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值