search
HomeBackend DevelopmentPython TutorialHow to use Python's combined data types

Combined data type

1 List

Expression of list
  • Sequence type: Internal elements have positional relationships and can be accessed through position numbers Element

  • The list is a sequence type that can use multiple types of elements and supports the addition, deletion, search, and modification operations of elements

ls = ["Python", 1989, True, {"version": 3.7}]
ls
['Python', 1989, True, {'version': 3.7}]
  • Another way to generate: list (iterable object)

  • Iterable objects include: strings, tuples, sets, range(), etc.

String to list

list("欢迎订阅本专栏")
['欢', '迎', '订', '阅', '本', '专', '栏']

Tuple to list

list(("我", "们", "很", "像"))
['我', '们', '很', '像']

Collection to list

list({"李雷", "韩梅梅", "Jim", "Green"})
['Green', 'Jim', '李雷', '韩梅梅']

Special range()

for i in [0, 1, 2, 3, 4, 5]:
    print(i)
0
1
2
3
4
5
for i in range(6):
    print(i)
0
1
2
3
4
5
  • range(start number, stop number, number interval)

If the starting number is defaulted, it defaults to 0

must include the stopping number, but note that the stopping number cannot be taken

The default number interval is 1

for i in range(1, 11, 2):
    print(i)
1
3
5
7
9
  • range() to list

list(range(1, 11, 2))
[1, 3, 5, 7, 9]

list Properties

  • The length of the list——len(list)

ls = [1, 2, 3, 4, 5]
len(ls)
5
  • The index of the list—— Identical to strings of the same sequence type

Variable name [position number]

Forward index starts from 0
Reverse index starts from -1

cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
print(cars[0])
print(cars[-4])
BYD
BYD
  • Slice of list

Variable name [Start position: End position: Slice Interval]

cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
  • Forward slice

  • ##
print(cars[:3])     # 前三个元素,开始位置缺省,默认为0;切片间隔缺省,默认为1
['BYD', 'BMW', 'AUDI']
print(cars[1:4:2])  # 第二个到第四个元素 前后索引差为2
['BMW', 'TOYOTA']
print(cars[:])      # 获取整个列表,结束位置缺省,默认取值到最后
['BYD', 'BMW', 'AUDI', 'TOYOTA']
print(cars[-4:-2])  # 获取前两个元素
['BYD', 'BMW']
  • Reverse slice

cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
print(cars[:-4:-1])      # 开始位置缺省,默认为-1
print(cars[::-1])        # 获得反向列表
['TOYOTA', 'AUDI', 'BMW']
['TOYOTA', 'AUDI', 'BMW', 'BYD']
List operators
  • Use the form of ** list1 lis2 ** to implement list splicing

a = [1, 2]
b = [3, 4]
a+b            # 该用法用的不多
[1, 2, 3, 4]
  • Use  n*list  or  list*n  to realize multiple copies of the list

Initialize one of the lists Methods

[0]*10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
List operation methods

1. Add elements

  • Add elements at the end—— List.append(element to be added)

languages = ["Python", "C++", "R"]
languages.append("Java")
languages
['Python', 'C++', 'R', 'Java']
  • Insert element at any position - list.insert(position number, element to be added)

    at the position Number the corresponding element
    before inserting the element to be added

    languages.insert(1, "C")
    languages
    ['Python', 'C', 'C++', 'R', 'Java']
    and merge it into another list at the end - List 1.extend (List 2 )
  • append Add the entire list 2 as an element to list 1
languages.append(["Ruby", "PHP"])
languages
['Python', 'C', 'C++', 'R', 'Java', ['Ruby', 'PHP']]

extend Add the elements in list 2 to list 1 one by one, of course This can be achieved by addition.

languages = ['Python', 'C', 'C++', 'R', 'Java']
languages.extend(["Ruby", "PHP"])
languages
['Python', 'C', 'C++', 'R', 'Java', 'Ruby', 'PHP']

2. Delete the element

    Delete the element at position i in the list list.pop(position)
  • languages = ['Python', 'C', 'C++', 'R', 'Java']
    languages.pop(1)
    languages
    ['Python', 'C++', 'R', 'Java']
    Do not write position information, delete the last element by default
  • languages.pop()
    languages
    ['Python', 'C++', 'R']
    Delete the first occurrence in the list Elements to be deleted List.remove(Element to be deleted)
  • ##

    languages = ['Python', 'C', 'R', 'C', 'Java']
    languages.remove("C")    
    languages
    ['Python', 'R', 'C', 'Java']
    languages = ['Python', 'C', 'R', 'C', 'Java']
    while "C" in languages:
        languages.remove("C")    
    languages
    ['Python', 'R', 'Java']
  • 3. Find the element

in the list The position where the element to be checked appears for the first time list.index(element to be checked)
  • languages = ['Python', 'C', 'R','Java']
    idx = languages.index("R") 
    idx
    2
  • 4. Modify the element

Modify the element through the method of "index first and then assign value" list name[position]=new value
    languages = ['Python', 'C', 'R','Java']
    languages[1] = "C++"
    languages
    ['Python', 'C++', 'R', 'Java']

    5、列表的复制

    • 错误的方式:这种方式仅是相当于给列表起了一个别名

    languages = ['Python', 'C', 'R','Java']
    languages_2 = languages
    print(languages_2)
    ['Python', 'C', 'R', 'Java']
    languages.pop()
    print(languages)
    print(languages_2)
    ['Python', 'C', 'R']
    ['Python', 'C', 'R']
    • 正确的方式——浅拷贝

    当内容中也有列表这种可变的情况时,这时浅拷贝可能出问题,应该采用深拷贝。

    • 方法1:列表.copy()

    languages = ['Python', 'C', 'R','Java']
    languages_2 = languages.copy()
    languages.pop()
    print(languages)
    print(languages_2)
    ['Python', 'C', 'R']
    ['Python', 'C', 'R', 'Java']
    • 方法2:列表 [ : ]

    • 相当于对整个列表的切片

    languages = ['Python', 'C', 'R','Java']
    languages_3 = languages[:]
    languages.pop()
    print(languages)
    print(languages_3)
    ['Python', 'C', 'R']
    ['Python', 'C', 'R', 'Java']

    6、列表的排序

    • 使用列表.sort()对列表进行永久排序

    • 直接在列表上进行操作,无返回值

    • 默认是递增的排序

    ls = [2, 5, 2, 8, 19, 3, 7]
    ls.sort()
    ls
    [2, 2, 3, 5, 7, 8, 19]
    • 递减排列

    ls.sort(reverse = True)
    ls
    [19, 8, 7, 5, 3, 2, 2]
    • 使用sorted(列表)对列表进行临时排序

    • 原列表保持不变,返回排序后的列表

    ls = [2, 5, 2, 8, 19, 3, 7]
    ls_2 = sorted(ls)
    print(ls)
    print(ls_2)
    [2, 5, 2, 8, 19, 3, 7]
    [19, 8, 7, 5, 3, 2, 2]
    sorted(ls, reverse = True)
    [19, 8, 7, 5, 3, 2, 2]

    7、列表的翻转

    • 使用列表.reverse()对列表进行永久翻转

    • 直接在列表上进行操作,无返回值

    ls = [1, 2, 3, 4, 5]
    print(ls[::-1])
    ls
    [5, 4, 3, 2, 1]
    
    [1, 2, 3, 4, 5]
    ls.reverse()
    ls
    [5, 4, 3, 2, 1]

    8、使用for循环对列表进行遍历

    ls = [1, 2, 3, 4, 5]
    for i in ls:
        print(i)
    1
    2
    3
    4
    5

    2 元组

     元组的表达
    • 元组是一个可以使用多种类型元素,一旦定义,内部元素不支持增、删和修改操作的序列类型

    通俗的讲,可以将元组视作“不可变的列表”

    names = ("Peter", "Pual", "Mary")
    元组的操作
    • 不支持元素增加、元素删除、元素修改操作

    • 其他操作与列表的操作完全一致

    元组的常见用处

    打包与解包

    • 例1 返回值是打包成元组的形式

    def f1(x):              # 返回x的平方和立方
        return x**2, x**3   # 实现打包返回
    
    print(f1(3))
    print(type(f1(3)))      # 元组类型
    (9, 27)
    <class></class>
    a, b = f1(3)            # 实现解包赋值 
    print(a)
    print(b)
    9
    27
    • 例2

    • 采用zip函数进行打包

    numbers = [201901, 201902, 201903]
    name = ["小明", "小红", "小强"]
    list(zip(numbers,name))
    [(201901, '小明'), (201902, '小红'), (201903, '小强')]
    for number,name in zip(numbers,name):   # 每次取到一个元组,立刻进行解包赋值
        print(number, name)
    201901 小明
    201902 小红
    201903 小强

    3 字典

    字典的表达
    • 映射类型: 通过“键”-“值”的映射实现数据存储和查找

    • 常规的字典是无序的,仅可以通过键来对数据进行访问

    students = {201901: '小明', 201902: '小红', 201903: '小强'}
    students

    字典键的要求

    • 1、字典的键不能重复

    如果重复,前面的键就被覆盖了

    students = {201901: '小明', 201901: '小红', 201903: '小强'}
    students
    {201901: '小红', 201903: '小强'}
    • 2、字典的键必须是不可变类型,如果键可变,就找不到对应存储的值了

    • 不可变类型:数字、字符串、元组。  一旦确定,它自己就是它自己,变了就不是它了。

    • 可变类型:列表、字典、集合。  一旦确定,还可以随意增删改。因此这三个类型不能作为字典的键。

    d1 = {1: 3}
    d2 = {"s": 3}
    d3 = {(1,2,3): 3}

    上面没有报错,说明是合法的。

    d = {[1, 2]: 3}
    ---------------------------------------------------------------------------
    
    TypeError                                 Traceback (most recent call last)
    
    <ipython-input-68-bf7f06622b3f> in <module>
    ----> 1 d = {[1, 2]: 3}
    
    
    TypeError: unhashable type: 'list'</module></ipython-input-68-bf7f06622b3f>
    d = {{1:2}: 3}
    ---------------------------------------------------------------------------
    
    TypeError                                 Traceback (most recent call last)
    
    <ipython-input-69-188e5512b5fe> in <module>
    ----> 1 d = {{1:2}: 3}
    
    
    TypeError: unhashable type: 'dict'</module></ipython-input-69-188e5512b5fe>
    d = {{1, 2}: 3}
    ---------------------------------------------------------------------------
    
    TypeError                                 Traceback (most recent call last)
    
    <ipython-input-70-c2dfafc1018a> in <module>
    ----> 1 d = {{1, 2}: 3}
    
    
    TypeError: unhashable type: 'set'</module></ipython-input-70-c2dfafc1018a>
    字典的性质
    • 字典的长度——键值对的个数

    students = {201901: '小明', 201902: '小红', 201903: '小强'}
    len(students)
    3
    • 字典的索引

    通过 字典[键] 的形式来获取对应的值

    students = {201901: '小明', 201902: '小红', 201903: '小强'}
    students[201902]
    '小红'
    字典的操作方法

    1、增加键值对

    • 变量名[新键] = 新值

    students = {201901: '小明', 201902: '小红', 201903: '小强'}
    students[201904] = "小雪"
    students
    {201901: '小明', 201902: '小红', 201903: '小强', 201904: '小雪'}

    2、删除键值对

    • 通过del 变量名[待删除键]

    students = {201901: '小明', 201902: '小红', 201903: '小强'}
    del students[201903]
    students
    {201901: '小明', 201902: '小红'}
    • 通过变量名.pop(待删除键)

    students = {201901: '小明', 201902: '小红', 201903: '小强'}
    value = students.pop(201903)   # 删除键值对,同时获得删除键值对的值
    print(value)
    print(students)
    小强
    {201901: '小明', 201902: '小红'}
    • 变量名.popitem() 随机删除一个键值对,并以元组返回删除键值对

    students = {201901: '小明', 201902: '小红', 201903: '小强'}
    key, value = students.popitem()
    print(key, value)
    print(students)
    201903 小强
    {201901: '小明', 201902: '小红'}

    3、修改值

    • 通过先索引后赋值的方式对相应的值进行修改

    students = {201901: '小明', 201902: '小红', 201903: '小强'}
    students[201902] = "小雪"
    students
    {201901: '小明', 201902: '小雪', 201903: '小强'}

    4、d.get( )方法

    d.get(key,default) 从字典d中获取键key对应的值,如果没有这个键,则返回default

    • 小例子:统计"牛奶奶找刘奶奶买牛奶"中字符的出现频率

    s = "牛奶奶找刘奶奶买牛奶"
    d = {}
    print(d)
    for i in s:
        d[i] = d.get(i, 0)+1 # 如果该字符第一次出现,则返回default 0 ,然后+1统计。如果之前就有i这个键,则返回该 key i 所对应的值。
        print(d)
    # print(d)
    {}
    {'牛': 1}
    {'牛': 1, '奶': 1}
    {'牛': 1, '奶': 2}
    {'牛': 1, '奶': 2, '找': 1}
    {'牛': 1, '奶': 2, '找': 1, '刘': 1}
    {'牛': 1, '奶': 3, '找': 1, '刘': 1}
    {'牛': 1, '奶': 4, '找': 1, '刘': 1}
    {'牛': 1, '奶': 4, '找': 1, '刘': 1, '买': 1}
    {'牛': 2, '奶': 4, '找': 1, '刘': 1, '买': 1}
    {'牛': 2, '奶': 5, '找': 1, '刘': 1, '买': 1}

    5、d.keys( ) d.values( )方法

    把所有的key,value 单独拿出来。

    students = {201901: '小明', 201902: '小红', 201903: '小强'}
    print(list(students.keys()))
    print(list(students.values()))
    [201901, 201902, 201903]
    ['小明', '小红', '小强']

    6、d.items( )方法及字典的遍历

    print(list(students.items()))
    for k, v in students.items():#进行解包
        print(k, v)
    [(201901, '小明'), (201902, '小红'), (201903, '小强')]
    201901 小明
    201902 小红
    201903 小强

    4 集合

    集合的表达

    • 一系列互不相等元素的无序集合(互斥)

    • 元素必须是不可变类型:数字,字符串或元组,可视作字典的键

    • 可以看做是没有值,或者值为None的字典

    students = {"小明", "小红", "小强", "小明"}   #可用于去重
    students
    {'小强', '小明', '小红'}
    集合的运算
    • 小例子 通过集合进行交集并集的运算

    Chinese_A = {"刘德华", "张学友", "张曼玉", "钟楚红", "古天乐", "林青霞"}
    Chinese_A
    {'刘德华', '古天乐', '张学友', '张曼玉', '林青霞', '钟楚红'}
    Math_A = {"林青霞", "郭富城", "王祖贤", "刘德华", "张曼玉", "黎明"}
    Math_A
    {'刘德华', '张曼玉', '林青霞', '王祖贤', '郭富城', '黎明'}
    • 语文和数学两门均为A的学员

    • S & T 返回一个新集合,包括同时在集合S和T中的元素

    Chinese_A & Math_A
    {'刘德华', '张曼玉', '林青霞'}
    • 语文或数学至少一门为A的学员

    • S | T 返回一个新集合,包括集合S和T中的所有元素

    Chinese_A | Math_A
    {'刘德华', '古天乐', '张学友', '张曼玉', '林青霞', '王祖贤', '郭富城', '钟楚红', '黎明'}
    • 语文数学只有一门为A的学员

    • S ^ T 返回一个新集合,包括集合S和T中的非共同元素

    Chinese_A ^ Math_A
    {'古天乐', '张学友', '王祖贤', '郭富城', '钟楚红', '黎明'}
    • 语文为A,数学不为A的学员

    • S - T 返回一个新集合,包括在集合S但不在集合T中的元素

    Chinese_A - Math_A
    {'古天乐', '张学友', '钟楚红'}
    • 数学为A,语文不为A的学员

    Math_A - Chinese_A
    {'王祖贤', '郭富城', '黎明'}
     集合的操作方法
    • 增加元素——S.add(x)

    stars = {"刘德华", "张学友", "张曼玉"}
    stars.add("王祖贤")
    stars
    {'刘德华', '张学友', '张曼玉', '王祖贤'}
    • 移除元素——S.remove(x)

    stars.remove("王祖贤")
    stars
    {'刘德华', '张学友', '张曼玉'}
    • 集合的长度——len(S)

    len(stars)
    3
    • 集合的遍历——借助for循环

    for star in stars:
        print(star)
    张学友
    张曼玉
    刘德华

    The above is the detailed content of How to use Python's combined data types. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

    Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

    Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

    Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

    Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

    Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

    Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

    Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

    Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

    Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

    Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

    Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

    Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

    Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

    Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

    Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment