Table of Contents
1. Sequence:
2. List: [a1, a2], variable data type
1. Creation of a list
2. Composite list and multidimensional list
3. List index value
4. List modification
3. List comprehension
1. List comprehension writing form:
2. The nested
4. Basic operations of lists
5. List related functions
6. Tuple (tuple): (a1 , a2)
1. Creation of tuples
2. Tuple operations
3, namedtuple (named tuple): An upgraded version of Python tuples
Home Backend Development Python Tutorial How to use complex data types in Python

How to use complex data types in Python

Jun 04, 2023 am 09:22 AM
python

1. Sequence:

Sequence is a base class type. Sequence extension types include: string, tuple and list

How to use complex data types in Python

Sequences can be performed Operations include indexing, slicing, adding, multiplying, and checking members.

In addition, Python has built-in methods for determining the length of a sequence and determining the largest and smallest elements.

2. List: [a1, a2], variable data type

List: List is an extension of sequence type, very commonly used

1. Creation of a list

  • The list is a sequence type and can be modified at will after creation

  • Use square brackets [] or list() to create , use commas to separate the elements.

  • Each element type in the list can be different, and there is no length limit

hobby_list = [hobby, 'run', 'girl']

print(id(hobby_list)) # 4558605960
print(type(hobby_list)) # 
print(hobby_list) # ['read', 'run', 'girl']
Copy after login

If you want to initialize the length to 10 List

list_empty = [None]*10
print(list_empty)
# [None, None, None, None, None, None, None, None, None, None]
Copy after login

Use the range() function to create a list:

hobby_list = list(range(5))
# [0, 1, 2, 3, 4]
Copy after login

2. Composite list and multidimensional list

hobby_list = ['read', 'run',['girl_name', 18, 'shanghai'] ]
print(hobby_list[2][1])#  取出girl的年龄 18
Copy after login

python creates a two-dimensional list and sets the required parameters Just write cols and rows

list_2d = [[0 for i in range(5)] for i in range(5)]
list_2d[0].append(3)
list_2d[0].append(5)
list_2d[2].append(7)
print(list_2d)
# [[0, 0, 0, 0, 0, 3, 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 7], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Copy after login

The following example converts a 3X4 matrix list into a 4X3 list:

# 以下实例展示了3X4的矩阵列表:
matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]

# 以下实例将3X4的矩阵列表转换为4X3列表:
transposed=[[row[i] for row in matrix] for i in range(4)]
print(transposed)
# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

# 以下实例也可以使用以下方法来实现:
transposed = []
for i in range(4):
    transposed.append([row[i] for row in matrix])
print(transposed)
# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
Copy after login

3. List index value

The index sequence number starts from 0 .

hobby_list = ['read', 'run', 'girl']
# 索引序号      0       1      2

print(hobby_list[1])#  取出第二个爱好 <code>run
Copy after login

4. List modification

You can modify or update the data items of the list. You can also use the append() method to add list items,

hobby_list = [&#39;read&#39;, &#39;run&#39;, &#39;girl&#39;]
hobby_list[0] = &#39;write&#39;
Copy after login

List method This makes the list easy to use as a stack. For a specific data structure like a stack, the last element inserted is the first to be removed (first in, last out).

Use the append() method to add an element to the top of the stack. Use the pop() method to remove the element at the top of the stack without specifying an index.

  • append: Add an element x at the end of the list ls

  • pop(): Move Remove an element in the list (the last element by default) and return the value of the element

For example:

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print(stack)
# [3, 4, 5, 6, 7]

print(stack.pop())
# 7
print(stack)
# [3, 4, 5, 6]
print(stack.pop())
# 6
print(stack.pop())
# 5

print(stack)
# [3, 4]
Copy after login

3. List comprehension

List comprehensions provide a simple way to create lists from sequences. Typically applications apply some operations to each element of a sequence and use the result as an element to generate a new list, or create a subsequence based on certain criteria.

Every list comprehension begins with for followed by an expression, and then zero or more for or if clauses.

The generated list is defined by the expressions in the context that follow the for and if statements. If you want the expression to derive a tuple, you must use parentheses.

1. List comprehension writing form:

  • [expression for variable in list]

  • [expression for Variable in list if condition]

Example:

print([i for i in range(10)] )  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print([i ** 2 for i in range(10)])  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  
print([0 for i in range(5)])  #[0, 0, 0, 0, 0]

name_list = [&#39;nick&#39;, &#39;sean&#39;, &#39;jason&#39;, &#39;tank&#39;]
for n in [name if name == &#39;nick&#39; else name + &#39;_a&#39; for name in name_list] :
    print(n)  # &#39;nick&#39;, &#39;sean_a&#39;, &#39;jason_a&#39;, &#39;tank_a&#39;

li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print( [x ** 2 for x in li]) # [1, 4, 9, 16, 25, 36, 49, 64, 81]
print( [x ** 2 for x in li if x > 5]) # [36, 49, 64, 81]
print(dict([(x, x * 10) for x in li])) # {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90} #生成字典

vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
sq = [vec2[i] + vec2[i] for i in range(len(vec))]  # 实现列表相加
print(sq)
# [6, 7, -3]

testList = [1, 2, 3, 4]

def mul2(x):
    return x * 2


print([mul2(i) for i in testList]) #使用复杂表达式或嵌套函数:
# [2, 4, 6, 8]
Copy after login

2. The nested

statements of the list comprehension are nested relationships.

The second statement on the left is the outermost layer, go one level to the right, and the first statement on the left is the last level.

[x*y for x in range(1,5) if x > 2 for y in range(1,4) if y < 3]
Copy after login

His execution order is:

for x in range(1,5)
    if x > 2
        for y in range(1,4)
            if y < 3
                x*y
Copy after login

Example

print( [ (x, y) for x in range(10) if x % 2 if x > 3 for y in range(10) if y > 7 if y != 8]) #生成元组
# [(5, 9), (7, 9), (9, 9)]

print([x * y for x in [1, 2, 3] for y in [1, 2, 3]])
# [1, 2, 3, 2, 4, 6, 3, 6, 9]
Copy after login

4. Basic operations of lists

ls1 = [&#39;python&#39;, 123]
ls2 = [&#39;java&#39;, 456]
print(ls1 * 2);  # [&#39;python&#39;, 123, &#39;python&#39;, 123] 将列表复制n次。
print(ls1 + ls2);  # [&#39;python&#39;, 123, &#39;java&#39;, 456] 连接两个列表
 
name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
del name_list[2]  # 删除索引2位置后的元素 
print(name_list)  # [&#39;nick&#39;, &#39;jason&#39;, &#39;sean&#39;]

del name_list[2:4] # 从列表中删除切片 ,删除第i-j位置的元素 
print(name_list)  # [&#39;nick&#39;, &#39;jason&#39;]

del name_list[:] #清空整个列表
print(name_list)  # []
del a  # 用 del 删除实体变量:


name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
print(&#39;tank sb&#39; in name_list)  #  成员运算:in; False
print(&#39;nick handsome&#39; not in name_list)  # 成员运算:in;True


name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
for name in name_list:  # for循环
    print(name)


a = [&#39;Google&#39;, &#39;Baidu&#39;, &#39;Runoob&#39;, &#39;Taobao&#39;, &#39;QQ&#39;]
for i in range(len(a)): # 结合range()和len()函数以遍历一个序列的索引
    print(i, a[i])
# 0 Google 1 Baidu 2 Runoob 3 Taobao 4 QQ


name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
print(name_list[0:3:2] )  # 切片  [&#39;nick&#39;, &#39;tank&#39;]
Copy after login

Example: There is the following list, and the list elements are Cannot hash type, remove duplicates, get a new list, and the new list must maintain the original order of the list

stu_info_list = [
    {&#39;name&#39;: &#39;nick&#39;, &#39;age&#39;: 19, &#39;sex&#39;: &#39;male&#39;},
    {&#39;name&#39;: &#39;egon&#39;, &#39;age&#39;: 18, &#39;sex&#39;: &#39;male&#39;},
    {&#39;name&#39;: &#39;tank&#39;, &#39;age&#39;: 20, &#39;sex&#39;: &#39;female&#39;},
    {&#39;name&#39;: &#39;tank&#39;, &#39;age&#39;: 20, &#39;sex&#39;: &#39;female&#39;},
    {&#39;name&#39;: &#39;egon&#39;, &#39;age&#39;: 18, &#39;sex&#39;: &#39;male&#39;},
]

new_stu_info_list = []
for stu_info in stu_info_list:
    if stu_info not in new_stu_info_list:
        new_stu_info_list.append(stu_info)

for new_stu_info in new_stu_info_list:
    print(new_stu_info)
Copy after login
name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
print(len(name_list))  # 4 列表元素个数:len;
print(min(name_list))  # jason 返回序列s的最小元素;
print(max(name_list))  # tank 返回序列s的最大元素

name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
name_list.insert(1, &#39;handsome&#39;) # insert(i,x):在列表的第i位置增加元素x 
print(name_list)  # [&#39;nick&#39;, &#39;handsome&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]

name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
print(name_list.remove(&#39;nick&#39;))  # remove(x):将列表ls中出现的第一个元素x删除 ,None ;
print(name_list)  # [&#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]

name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
print(name_list.count(&#39;nick&#39;))  # 1  ;统计某个元素在列表中出现的次数

name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
print(name_list.index(&#39;nick&#39;))  # 0;返回元素所在列表中的索引

name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
name_list.clear() # 删除列表中所有元素 
print(name_list)  # []

name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
print(name_list.copy())  # 生成一个新列表,赋值原列表中所有元素  [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]

name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
name_list2 = [&#39;nick handsome&#39;]
name_list.extend(name_list2) # 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
print(name_list)  # [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;, &#39;nick handsome&#39;]

name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
name_list.reverse() # 将列表ls中的元素反转 
print(name_list)  # [&#39;sean&#39;, &#39;tank&#39;, &#39;jason&#39;, &#39;nick&#39;]

name_list = [&#39;nick&#39;, &#39;jason&#39;, &#39;tank&#39;, &#39;sean&#39;]
name_list.sort() # 排序,使用用sort列表的元素必须是同类型的
 
print(name_list)  # [&#39;jason&#39;, &#39;nick&#39;, &#39;sean&#39;, &#39;tank&#39;]

name_list.sort(reverse=True) # 倒序
print(name_list)  # [&#39;tank&#39;, &#39;sean&#39;, &#39;nick&#39;, &#39;jason&#39;]
Copy after login

6. Tuple (tuple): (a1 , a2)

1. Creation of tuples

Tuples are a list type and cannot be modified once created.

color = (0x001100, "blue", creature) # 使用小括号 () 或 tuple() 创建,元素间用逗号分隔。
print(type(color))  # 

creature = "cat", "dog", "tiger", "human" # 可以使用或不使用小括号。即元组由若干逗号分隔的值组成。
print(type(creature))  #
Copy after login

Note the difference from strings:

name_str = (&#39;egon&#39;)  # ()只是普通包含的意思
name_tuple = (&#39;egon&#39;,)  # 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作字符串使用:

print(type(name_str))  # 
print(type(name_tuple))  #
Copy after login

2. Tuple operations

Index value, slicing (ignoring the head) tail, step size), length len, member operations in and not in, loops, count, index, etc. are all the same as the list, but the value is not changed.

The element values ​​in the tuple are not allowed to be modified, but we can connect and combine the tuples, as shown in the following example:

tup1 = (12, 34.56);
tup2 = (&#39;abc&#39;, &#39;xyz&#39;)

# 以下修改元组元素操作是非法的。
# tup1[0] = 100

# 创建一个新的元组
tup3 = tup1 + tup2;
print(tup3)  # (12, 34.56, &#39;abc&#39;, &#39;xyz&#39;)
Copy after login

3, namedtuple (named tuple): An upgraded version of Python tuples

from collections import namedtuple

User = namedtuple(&#39;User&#39;, &#39;name sex age&#39;) # 定义一个namedtuple类型User,并包含name,sex和age属性。
user = User(name=&#39;Runoob&#39;, sex=&#39;male&#39;, age=12) # 创建一个User对象

print(user.age)  # 12
Copy after login

The above is the detailed content of How to use complex data types in Python. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles