Table of Contents
Combined data type
1 List
Expression of list
list Properties
2 元组
 元组的表达
元组的操作
元组的常见用处
3 字典
字典的表达
字典的性质
字典的操作方法
4 集合
集合的表达
集合的运算
 集合的操作方法
Home Backend Development Python Tutorial How to use Python's combined data types

How to use Python's combined data types

May 11, 2023 pm 12:10 PM
python

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
Copy after login
['Python', 1989, True, {'version': 3.7}]
Copy after login
  • Another way to generate: list (iterable object)

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

String to list

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

Tuple to list

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

Collection to list

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

Special range()

for i in [0, 1, 2, 3, 4, 5]:
    print(i)
Copy after login
0
1
2
3
4
5
Copy after login
Copy after login
for i in range(6):
    print(i)
Copy after login
0
1
2
3
4
5
Copy after login
Copy after login
  • 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)
Copy after login
1
3
5
7
9
Copy after login
  • range() to list

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

list Properties

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

ls = [1, 2, 3, 4, 5]
len(ls)
Copy after login
5
Copy after login
  • 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"]
Copy after login
Copy after login
Copy after login
print(cars[0])
print(cars[-4])
Copy after login
BYD
BYD
Copy after login
  • Slice of list

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

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

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

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

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

Initialize one of the lists Methods

[0]*10
Copy after login
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Copy after login
List operation methods

1. Add elements

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

languages = ["Python", "C++", "R"]
Copy after login
languages.append("Java")
languages
Copy after login
['Python', 'C++', 'R', 'Java']
Copy after login
Copy after login
Copy after login
  • 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
    Copy after login
    ['Python', 'C', 'C++', 'R', 'Java']
    Copy after login
    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
Copy after login
['Python', 'C', 'C++', 'R', 'Java', ['Ruby', 'PHP']]
Copy after login

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
Copy after login
['Python', 'C', 'C++', 'R', 'Java', 'Ruby', 'PHP']
Copy after login

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
    Copy after login
    ['Python', 'C++', 'R', 'Java']
    Copy after login
    Copy after login
    Copy after login
    Do not write position information, delete the last element by default
  • languages.pop()
    languages
    Copy after login
    ['Python', 'C++', 'R']
    Copy after login
    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
    Copy after login
    ['Python', 'R', 'C', 'Java']
    Copy after login
    languages = ['Python', 'C', 'R', 'C', 'Java']
    while "C" in languages:
        languages.remove("C")    
    languages
    Copy after login
    ['Python', 'R', 'Java']
    Copy after login
  • 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
    Copy after login
    2
    Copy after login
  • 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
    Copy after login
    ['Python', 'C++', 'R', 'Java']
    Copy after login
    Copy after login
    Copy after login

    5、列表的复制

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

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

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

    • 方法1:列表.copy()

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

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

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

    6、列表的排序

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

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

    • 默认是递增的排序

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

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

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

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

    7、列表的翻转

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

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

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

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

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

    2 元组

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

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

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

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

    元组的常见用处

    打包与解包

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

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

    • 采用zip函数进行打包

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

    3 字典

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

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

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

    字典键的要求

    • 1、字典的键不能重复

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

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

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

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

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

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

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

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

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

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

    1、增加键值对

    • 变量名[新键] = 新值

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

    2、删除键值对

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

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

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

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

    3、修改值

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

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

    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)
    Copy after login
    {}
    {'牛': 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}
    Copy after login

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

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

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

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

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

    4 集合

    集合的表达

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    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 of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    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 Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Jul 01, 2024 am 07:22 AM

    Google AI has started to provide developers with access to extended context windows and cost-saving features, starting with the Gemini 1.5 Pro large language model (LLM). Previously available through a waitlist, the full 2 million token context windo

    How to download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

    How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

    How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

    The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

    How to search deepseek How to search deepseek Feb 19, 2025 pm 05:18 PM

    Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

    How to program deepseek How to program deepseek Feb 19, 2025 pm 05:36 PM

    DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

    How to use deepseek to settle accounts How to use deepseek to settle accounts Feb 19, 2025 pm 04:36 PM

    Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

    The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

    Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

    Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

    Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

    See all articles