Home  >  Article  >  Backend Development  >  How to use complex data types in Python

How to use complex data types in Python

WBOY
WBOYforward
2023-06-04 09:22:16897browse

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']

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]

Use the range() function to create a list:

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

2. Composite list and multidimensional list

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

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]]

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]]

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

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;

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]

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]

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]

His execution order is:

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

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]

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;]

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)

5. List related functions

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;]

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))  #

Note the difference from strings:

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

print(type(name_str))  # 
print(type(name_tuple))  #

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;)

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

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:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete