zoukankan      html  css  js  c++  java
  • python基础之列表、元组和字典

    列表

    列表定义:[]内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素

    特性:

      1.可存放多个值

      2.可修改指定索引位置对应的值,可变

      3.按照从左到右的顺序定义列表元素,下标从0开始顺序访问,有序

    创建列表:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    list_test1=['hello',12,'ok']
    list_test2=list('abc')
    list_test3=list(['hello',12,'ok'])
    print(list_test1)
    print(list_test2)
    print(list_test3)
    
    输出结果:
    ['hello', 12, 'ok']
    ['a', 'b', 'c']
    ['hello', 12, 'ok']

    列表常用操作:

    索引

    list_test1=['hello',12,'ok',[14,19]]
    print(list_test1.index('hello'))  #输出结果为:0
    print(list_test1.index([14,19]))  #输出结果为:3
    print(list_test1.index(19))    #该操作会报ValueError: 19 is not in list,因为index()只能索引一级元素,无法索引子列表的子元素

    追加:从最后添加元素

    list_test1=['hello',12,'ok',[14,19]]
    list_test1.append(1994)
    print(list_test1)
    list_test1.append('txt')
    print(list_test1)
    
    输出结果:
    ['hello', 12, 'ok', [14, 19], 1994]
    ['hello', 12, 'ok', [14, 19], 1994, 'txt']

    插入:指定位置添加元素

    list_test1=['hello',12,'ok',[14,19]]
    list_test1.insert(3,'exe')    #数字为索引位置,exe为插入的字符串
    print(list_test1)
    list_test1.insert(0,'txt')
    print(list_test1)
    
    输出结果:
    ['hello', 12, 'ok', 'exe', [14, 19]]
    ['txt', 'hello', 12, 'ok', 'exe', [14, 19]]

    删除:

    pop()不加索引默认是从最后一个元素删除

    list_test1=['hello',12,'ok',[14,19]]
    list_test1.pop()
    print(list_test1)
    list_test1.pop(0)
    print(list_test1)
    
    输出结果:
    ['hello', 12, 'ok']
    [12, 'ok']

    remove()从匹配的第一个开始删除

    list_test1=['ok','hello','ok',12,'ok',[14,19]]
    list_test1.remove('ok')
    print(list_test1)
    
    输出结果:
    ['hello', 'ok', 12, 'ok', [14, 19]]

    长度:列表中一个元素算一个长度,conut()方法用于计算某个元素的个数

    list_test1=['hello',12,'ok',[14,19]]
    print(len(list_test1))
    list_test1=['hello','ok',12,'ok',[14,19]]
    print(list_test1.count('ok'))

    切片

    list_test1=['a','c','f',1,2,3,'2a','3b']
    print(list_test1[5])
    print(list_test1[3:5])
    print(list_test1[1:6:2])
    
    输出结果:
    3
    [1, 2]
    ['c', 1, 3]

    循环:通过索引遍历一个列表

    l=[1,'a',3,[4,5]]
    l_size=len(l)
    for index in range(l_size):
        value=l[index]
        if type(value) is list:
            for i in range(len(value)):
                print(value[i])
        else:
            print(value)
    
    输出结果:
    1
    a
    3
    4
    5

    包含:直接遍历一个列表

    l=[1,'a',3,[4,5]]
    for i in l:
        x=i
        if type(x) is int:
            print(x)
        else:
            for a in x:
                print(a)
    
    输出结果:
    1
    a
    3
    4
    5

    拷贝

    list_test1=['a','c','f']
    list_test2=list_test1.copy()
    print(list_test2)
    
    输出结果
    ['a', 'c', 'f']

    扩展:将另一个list的所有元素依次加到一个list中

    list_test1=['a','c','f']
    list_test1.extend([1,2,3])
    print(list_test1)
    
    输出结果
    ['a', 'c', 'f', 1, 2, 3]

    清空:清除所有的元素

    list_test1=['a','c','f']
    list_test1.clear()
    print(list_test1)
    
    输出结果:
    []

    反转

    list_test1=['ok','hello','ok',12,'ok',[14,19]]
    list_test1.reverse()
    print(list_test1)
    
    输出结果:
    [[14, 19], 'ok', 12, 'ok', 'hello', 'ok']

    排序:列表只能是纯字符串或者是纯数字

    list_test1=['a','c','f']
    print(list_test1)
    list_test1.sort()
    list_test1.sort(reverse=True)  #打开反转功能,即倒序
    print(list_test1)
    
    输出结果:
    ['a', 'c', 'f']
    ['f', 'c', 'a']

    元组

    元组定义:与列表类似,只不过[]改成()

    特性

      1.可存放多个值

      2.不可变

      3.按照从左到右的顺序定义元组元素,下标从0开始顺序访问,有序

    创建元组:

    tuple_test1 = (11, 'aa', 3, 'bc', 'aa','aa')
    tuple_test2 = tuple((11, 22, 33, 44, 55))
    print(tuple_test1)
    print(tuple_test2)
    
    输出结果:
    (11, 'aa', 3, 'bc', 'aa', 'aa')
    (11, 22, 33, 44, 55)

    元组常用操作:

    元组的操作和列表的操作类似,但是由于元组是不可变类型,所以没有添加、删除、插入等操作方法

    索引

    tupel_test1=('hello',12,'ok',(14,19),['a','b'])
    print(tupel_test1.index('hello'))  #输出结果为0
    print(tupel_test1.index((14,19)))  #输出结果为3
    print(tupel_test1.index(19))    #报错,同list一样,无法索引子元组的元素

    切片

    tupel_test1=('hello',12,'ok',(14,19),['a','b'])
    print(tupel_test1[1])
    print(tupel_test1[3][1])
    print(tupel_test1[4][0])
    
    输出结果:
    12
    19
    a

    长度

    tupel_test1=('hello','ok',12,'ok',(14,19),['a','b'])
    print(tupel_test1.count('ok'))
    
    输出结果:
    2

    循环

    tuple_test1=('hello','ok',12,'ok',(14,19))
    t_size=len(tuple_test1)
    for index in range(t_size):
        value=tuple_test1[index]
        if type(value) is tuple:
            for i in range(len(value)):
                print(value[i])
        else:
            print(value)
    
    输出结果
    hello
    ok
    12
    ok
    14
    19

    包含

    t=(1,'a',3,[4,5])
    t_size=len(t)
    for index in range(t_size):
        value=t[index]
        if type(value) is list:
            for i in range(len(value)):
                print(value[i])
        else:
            print(value)
    
    输出结果:
    1
    a
    3
    4
    5

    字典

    定义:{key1:value1,key2:value2},key-value结构,key必须可hash,即不可变类型

    a=1
    b='abc'
    c=[1,2]
    d=('a','b')
    print(hash(a))
    print(hash(b))
    # hash(c)  #列表不可hash,会抛出一个TypeError错误
    print(hash(d))
    
    输出结果
    1
    -5597926949654223802
    4804482478488461503

    特性:

      1.可存放多个值

      2.可修改指定key对应的值,可变

      3.无序,每次print顺序都不一样

    创建字典:

    person1 = {"name": "bob", 'age':18}
    person2 = dict(name='alex', age=19)
    person3 = dict({"name": "natasha", 'age':20})
    person4 = dict((['name','bob'],['age',10]))
    print(person1)
    print(person2)
    print(person3)
    print(person4)

    输出结果:
    {'name': 'bob', 'age': 18}
    {'name': 'alex', 'age': 19}
    {'name': 'natasha', 'age': 20}
    {'name': 'bob', 'age': 10}

    转换成字典:值只能有一个

    d5={}.fromkeys(['name','age'],None)
    print(d5)
    d6={}.fromkeys(['name','age'],['bob',18])
    print(d6)
    
    输出结果
    {'name': None, 'age': None}
    {'name': ['bob', 18], 'age': ['bob', 18]}

    更新:有的覆盖,没有的添加,原有的保留

    d={'name':'alex'}
    d1={'name':'alexbb','age':15}
    d.update(d1)
    print(d)
    
    输出结果
    {'name': 'alexsb', 'age': 15}

    转换元组:转换的类型并不是tuble类型,但是可以像tuple一样调用,如for i in d.items:

    d={'x':1,'y':1}
    print(d.items())
    
    输出结果
    dict_items([('x', 1), ('y', 1)])

    转换元组删除

    d={'x':1,'y':1}
    print(d.items())
    d.popitem()
    print(d.items())
    
    输出结果
    dict_items([('x', 1), ('y', 1)])
    dict_items([('x', 1)])

    增加一个键值对:如果键已存在,则不添加不更新

    d={'x':1,'y':1}
    d.setdefault('x','1')
    print(d)
    d.setdefault('x','3')
    print(d)
    d.setdefault('k','aaa')
    print(d)
    
    输出结果
    {'x': 1, 'y': 1}
    {'x': 1, 'y': 1}
    {'x': 1, 'y': 1, 'k': 'aaa'}

    索引

    person1 = {"name": "bob", 'age':18}
    print(person1['name'])
    
    输出结果
    bob

    新增

    person1 = {"name": "bob", 'age':18}
    person1['sex'] = 'male'
    print(person1)
    
    输出结果
    {'name': 'bob', 'age': 18, 'sex': 'male'}

    删除

    person1 = {"name": "bob", 'age':18}
    print(person1.pop('name'))
    print(person1)
    
    输出结果
    bob
    {'age': 18}

    键、值、键值对

    #列出包含的key和value
    person1 = {"name": "bob", 'age':18}
    print(person1.keys())
    print(person1.values())
    
    输出结果
    dict_keys(['name', 'age'])    #数据类型为dict_keys
    dict_values(['bob', 18])    #数据类型为dict_values
    
    #检测是否存在某一个key
    print(person1.get('name'))
    print(person1.get('abc'))
    
    输出结果
    bob
    None    #没有该key抛出None

    循环

    person1 = {"name": "bob", 'age':18, 'sex':'male'}
    for x in person1.keys():
        y = person1[x]
        print(x,y)
    
    输出结果:
    name bob
    age 18
    sex male

    长度

    person1 = {"name": "bob", 'age':18}
    print(len(person1))
    
    输出结果:
    2
  • 相关阅读:
    阅读编程书籍的方法(转)
    Java 面向对象概念
    Python 统计文本中单词的个数
    Python 学习笔记(五)杂项
    在CentOS7环境下部署TiDB
    前端学习之路:第三章、来做个天气应用吧(1)
    前端学习之路:第二章、Vue-router和axios
    前端学习之路:第一章、开始使用Vue
    在Docker下搭建Apache+PHP+mysql环境的过程记录
    在基于Windows系统的PHP后端中引入Redis
  • 原文地址:https://www.cnblogs.com/lidagen/p/7049187.html
Copyright © 2011-2022 走看看