two basic types of data python

Chapter IV python basic data types two

Python combination of common data type Data type: lists, tuples.

4.1 List list

List describes

The list is the basic data type of the python ⼀, The language statement in other programming languages ​​have similar data types such as arrays of JS, java in the array, etc. It is surrounded by [], with each element Use ',' spaced and can store a variety of data types,

Define a common way:

lst = [1, 'Li Lei "," snow ", Ture, [1,8,0," Baidu "], (" me "," call "," meta "," group ")," ABC " { "my name": "dict dictionary"}, { "I called the collection", "collection"}]

li = [1,2,3,'123',True,[1,2,5]]   # 容器 任意类型都可以
列表 == 书包
    水杯
    衣服
    袜子
    钱包
        1,2,5

Second way is defined

Using the underlying list for loop "abc" may be iterative string type

li = list("abc")  
print(li)
['a', 'b', 'c']

Substring comparison list:

List can store large amounts of data, store a small amount of data sub-strings, can store a large amount of a zoomed python 32-bit data can be stored: 536,870,912 elements 64 can be stored: 1152921504606846975 ⽽ elements and column list is ordered ( order you save), an index, you can cut piece ⽅ still pictures will be convenient value.

4.2 List of indexing and slicing

Like comparing a list of strings has also ordered the index, slice, step.

4.2.1 Index

li = [1,2,3,"123",True]
    # 0 1 2  3     4    #列表对于的元素索引值从0开始取值
print(lst[0])           # 获取第⼀个元素 1
print(lst[1])           # 获取第二个元素 2
print(lst[2])           # 获取第三个个元素 3

Note: The list out what type of element is what type

li = [1,2,3,'123',True]
print(li[3],type(li[3]))    #获取第三个元素类型字符串str
123 <class 'str'>
print(li[4],type(li[4]))
True <class 'bool'>         #获取第四个元素类型布尔值bool

4.2.2 sliced

Slice list, using the index value (index) the table of contents of elements taken part.

Syntax: list [star: end]

Rule: care regardless tail, start capturing the start, end position to intercept, but not including the end elements.

The default starting from 0 to intercept

li = [1,2,3,"123",True]
    # 0 1 2   3      4      #从左边往右边切取(索引值)从0开始取(有序支持)
    # -5 -4 -3 -2   -1      #从右边往左边切取值(索引值)从-1开始取
print(li[:2])              #从0获取到2,不包含2 结果:[1, 2]
print(li[1:4])             #从1获取4,不包含4 结果:[2, 3, '123']
print(li[-1:])             #(取倒数第一个)从右边-1获取到0不包含0(对应方向为右边) 只取1个结果:True

4.2.3 a list of steps

Step is to take dancing, jumping a few steps take time, control the direction of value.

After slicing step or the original data type:

= S "Alex"
Print (type (S [. 1:. 3:. 1])) # sliced or the original data type <class 'STR'>
Print (type (Li [-1: -4: -1])) # <class 'list'>

Step: If is an integer, taken from left to right then from right to left is negative if the default is taken at -1...

Slice syntax: list [start: end: step] start: start position end: end position step: Step ⻓ (number of steps)

li = [1,2,3,"123",True]
    # 0 1 2   3      4      
    # -5 -4 -3 -2   -1
print(li[-1:-4:1])   
#取-1到-4的值,不包含-4,方向向右,结果值[]需引入步长值改变取值方向。
li = [1,2,3,"123",True,[1,2,3,False],]
    # 0 1 2   3     4       5
    # -6 -5 -4 -3  -2       -1

print(li[-1:-4:-2])     #从-1开始到-4取值,左方向跳2步到-5结束不包含-5结果:[[1, 2, 3, False], '123']
                      #公式算法类似:起始+步长 -1+-2 = -3往右边(倒着)跳2步,-3+-2=-5

4.3 List of increase, delete, change,

4.3.1 List of increase

list is a list of variable objects, operate directly on the original object.

li = [1,2,3,"123",True]
li[2] = "注意"
print(li)
[1, 2, '注意', '123', True]

str strings are immutable object, so any operation will not have any impact on the original string.

s = "123"
s[2] = "注意"
print(s)
#报错 TypeError: 'str' object does not support item assignment不允许改变

4.1.2 List of increase

append () increase:

Append mode, the default added to the end of the elements in the list.

Error writing: print (li.append ( 'too bright')) result value: None

li = [1,2,3,'alex',3,[1,2,3]]
     #0,1,2,  3,    4, 5
li.append('太亮')          # 追加  添加在末尾  添加的操作
print(li)
[1, 2, 3, 'alex', 3, [1, 2, 3], '太亮']

insert () insert

You need to specify the location (index) elements into the original elements of a backward movement, so the low efficiency (sequentially inserted into the memory address space)

Syntax: insert (seat, content)

li = [1,2,3,'alex',3,[1,2,3]]
li.insert(0,"太亮")   #插入第一个参数(索引),第二参数要插入的内容(效率特别低)
print(li)
['太亮', 1, 2, 3, 'alex', 3, [1, 2, 3]]

extend () iteration added

extend () to add the underlying principle similar to the iterative loop for sequentially the contents of each element of the string is split into sub-cycles back to the list.

li = [1,2,3]            # 扩展 -- 迭代添加  -- for
li.extend("abc")
print(li)
[1, 2, 3, 'a', 'b', 'c']

Add iterative realization of the principle;

li = [1,2,3]
for i in "abc":    #迭代添加开始
    li.append(i)    #迭代添加结束
print(li)
[1, 2, 3, 'a', 'b', 'c']

Int int, bool Boolean object can not be iterated

li = [1,2,3]        
li.extend(123)
print(li)
#报错TypeError: 'int' object is not iterable

List merge

l1 = [1, 2, 3]
l2 = ["a","b","c"]
print(l1+l2)
[1, 2, 3, 'a', 'b', 'c']

4.1.3 delete list

pop () list deletion process to delete the exception of pop returns a value, returns the contents are deleted, the default is to remove at the end of the element.

Syntax: pop (index) specified index (index) is deleted in parentheses.

li = [1,2,3,"abc",True]
li.pop(3)
print(li)

abc             # 被删除的内容
[1, 2, 3, True]   #删除后的结果

remove () to delete the specified element names be removed if the name of the element does not exist will throw an error.

li = [1,2,3,"abc",True]
li.remove(1)
print(li)

del Delete

Marked for deletion, clear the memory unused resources, free up space.

del python keyword is, the underlying principle will calculate the number of all elements appear, in memory were divided into statistics, automatically free up space

= Li [l, 2,3, "ABC", True]
del Li Li #del the entire container are deleted
print (li)

del supports indexing, slicing steps to delete

li = [1,2,3,"abc",True]
del li[2]               #del支持索引删除
del li[0:3]             #del支持切片删除
del li[::2]             #del支持步长删除
print(li)

clear () Clear

li = [1,2,3,"abc",True]
li.clear()                      #清空列表结果:[]
print(li)

4.1.4 modify the list

List element index, slice, step size changes.

Index list

li = ["水杯",2,3,"abc",]
li[1] = "奶瓶"                把二号元素替换成奶瓶
print(li)
['水杯', '奶瓶', 3, 'abc']

Slice list

li = ["水杯",2,3,"abc",]
i[1:3] = [1,2,3]   #在1到3范围添加列表[1,2,3],1-3区间会展开放
print(li)
['水杯', 1, 2, 3, 'abc']
li = ["水杯",2,3,"abc",]
li[1:3] = "abcd"
print(li)
['水杯', 'a', 'b', 'c', 'd', 'abc']
li = ["水杯",2,3,"abc",]
l2 = [1,2,3,4,66,7]

li[1:3] = l2[4:]       #l2[4:]从索引值4后面取出来的类型是列表[66,7]类型,迭代进去,可多可少。
print(li)
['水杯', 66, 7, 'abc']
li = ["水杯",2,3,"abc",]
li[1:2] = []      #从1-2范围全部变成空,不包含2
print(li)
['水杯', 3, 'abc']

A question:

li = [1,2,3,4,"abc",5]
li[0:2] = "ABCsadfsdf"    #li[0:2]出的结果[3,4,"abc",5]被"ABCsadfsdf"迭代添加
print(li)
['A', 'B', 'C', 's', 'a', 'd', 'f', 's', 'd', 'f', 3, 4, 'abc', 5]

Step:

On the interception of several elements into several elements

li = [ "glass", 2, 3, "abc",]
li [0: 3: 2] = "ABCABC" # error range is not clear, iterative position unable to find
print (li)

li = ["水杯",2,3,"abc",]
li[0:3:2] = [1,2,3],[1234]     #截取几个元素就放入几个元素
print(li)
[[1, 2, 3], 2, [1234], 'abc']

4.1.5 List of inquiry

List is an iteration object that can be checked for loop

#for循环
li = ["水杯",2,3,"abc",]
for em in li:
    print(em)

General Inquiries

li = [1,2,3,4]
print(li)
print(li[1])

A list of other actions: statistics, sorting, reverse, length

lst = ["太⽩", "太⿊",  "太⽩"] 
c = lst.count("太⽩")                 # 查询太⽩出现的次数 
print(c) 

lst = [1, 11, 22, 2] 
lst.sort()                              # 排序. 默认升序 
print(lst) l
st.sort(reverse=True)                   # 降序 
print(lst)


lst = ["太⽩白", "太⿊黑", "五⾊色", "银王", "⽇日天", "太⽩白"] 
print(lst) 
lst.reverse() 
print(lst)

l = len(lst)                             # 列列表的⻓长度 
print(l)

4.3.6 nested list

Drop operation using the dimension, layer by layer look like

lst = [1, "小白", "lisir", ["码农", ["可乐"], "王林林"]]
print(lst[2])                       # 找到lisir
print(lst[1:3])                     #找到'小白', 'lisir'
print(lst[1][1])                     #找到小白中的白

lst = [1, "white", "lisir" [ "Agricultural code" [ "Coke"], "Songs"]] will get lisir then zoomed therefore especially uppercase first character ⺟ mother again to throw back

lst = [1, "小白", "lisir", ["马疼", ["可乐"], "王林林"]]#将lisir拿到. 然后⾸首字⺟母⼤大写. 再扔回去
s = lst[2]          #将lisir拿到
s = s.capitalize()   #⾸首字⺟母⼤大写
lst[2] = s
print(lst)

Write:

lst = [1, "小白", "lisir", ["码农", ["可乐"], "王林林"]]
lst[2] = lst[2].capitalize()
print(lst)

The white becomes black

lst = [1, "小白", "lisir", ["码农", ["可乐"], "王林林"]]
lst[1]= lst[1].replace("白", "黑")
print(lst)

Code into the code farmers cloud

lst = [1, "小白", "lisir", ["码农", ["可乐"], "王林林"]]
lst[3][0] = lst[3][0].replace("农", "云")
print(lst[3][0])

Add to the list of Sprite

lst[3][1].append("雪碧")
print(lst)

4.3 yuan group tuple

Tuple: immutable commonly known as a separate warranty column list has been read-only column list, tuples are the basic data types of the python a ⼀, with ⼩ Use enclosed in parentheses, ⾥ ri ⾯ surface can put any type of data data, queries can. cycle can be. slice can. may save some any type of data, but they can not change. Store some data can not be modified.

tu = (1) is not separated by a comma in parentheses element itself is not a tuple.

tu = (1,) an element in the parentheses is separated by commas tuple

tu = () includes a small well is empty tuple

A tuple is an ordered index, sections, steps, data type is immutable

General application program in the configuration file, modify some of the data in order to prevent misuse

Query 4.3.1 tuples

tu = (1, 2, 3, "lisir", 6)
print(tu)
print(tu[1])            #索引
print(tu[1:1000])       #切片 返回的是切片前的数据类型
print(tu[::2])          #步长

Tuples for loop

tu = (1, 2, 3, "lisir", 6)
# for循环遍历元组
for el in tu:
    print(el)

About immutable, attention: individual cases from tuples ri immutable mean submenus and sub-submenus ⽽ element immutable submenus child elements inside the sub-elements can be changed, depending on whether submenus child element is a variable object.

Operation list elements inside the element can be added to the list element of the tuple

tu = (1, 2, [],3, "lisir", 6)
tu[2].append("hehe")     # 可以改了了. 没报错
tu[2].append("你好")
print(tu)

Tuple also count (), index (), len ()

4.3.2 nested tuples

tu = (1,2,3,(4,5,6,[6,7,8,(9,11,10),"abc"],"ABC"))
print(tu[3][3][3][1])  # [6,7,8,(9,11,10),"abc"]
print(tu[-1][-2][-1])

Guess you like

Origin www.cnblogs.com/yueling314/p/10994401.html