Python learning notes: basic data types! (tuple, list, dictionary)

Keywords: Python Pycharm crawler

Tuple tupe

Tuples are called read-only lists, that is, data can be queried but cannot be modified. Therefore, the slicing operation of strings is also applicable to tuples. Example: (1, 2, 3) ("a", "b", "c")

List list

List is one of the basic data types in python. Other languages also have data types similar to list. For example, it is called array in js. It is enclosed by [] and each element is separated by commas. It can store various data types, such as:

li = ['alex', 123,Ture,(1,2,3, 'wusir'), [1,2,3, 'Xiaoming',], {'name': 'alex'}]

Compared with strings, lists can store not only different data types, but also a large amount of data. The limit of 32-bit python is 536870912 elements, and the limit of 64 bit python is 1152921504606846975 elements. Moreover, the list is orderly, has index values, can be sliced, and is convenient to take values.

increase

li = [1,'a','b',2,3,'a']
li.insert(0,55) #Increase by index
print(li)
li.append('aaa') #Add to last
li.append([1,2,3]) #Add to last
print(li)
li.extend(['q,a,w']) #Iterative de increment
li.extend(['q,a,w','aaa'])
li.extend('a')
li.extend('abc')
li.extend('a,b,c')
print(li)
Output:
[55, 1, 'a', 'b', 2, 3, 'a']
[55, 1, 'a', 'b', 2, 3, 'a', 'aaa', [1, 2, 3]]
[55, 1, 'a', 'b', 2, 3, 'a', 'aaa', [1, 2, 3], 'q,a,w', 'q,a,w', 'aaa', 'a', 'a', 'b', 'c', 'a', ',', 'b', ',', 'c']

Delete

l1 = li.pop(1) #Delete by location, with return value
print(l1)
del li[1:3] #Delete according to the position, or delete the slice without return value.
print(li)
li.remove('a') #Delete by element
print(li)
li.clear() #clear list 
Output:
a
[1, 3, 'a']
[1, 3]

change

li = [1,'a','b',2,3,'a']
li[1] = 'dfasdfas'
print(li)
li[1:3] = ['a','b']
print(li)
Output:
[1, 'dfasdfas', 'b', 2, 3, 'a']
[1, 'a', 'b', 2, 3, 'a']

check

Slice to check, or cycle to check.

Other operations

count (the method counts the number of times an element appears in the list).

a = ["q","w","q","r","t","y"]
print(a.count("q"))

Index (the method is used to find the index position of the first match of a value from the list)

a = ["q","w","r","t","y"]
print(a.index("r"))

Sort (the method is used to sort the list in its original location).

The reverse (method stores the elements in the list in reverse).

a = [2,1,3,4,5]
a.sort() # it has no return value, so it can only print a
print(a)
a.reverse() # it also has no return value, so it can only print a
print(a)

Dictionary dict

Dictionary is the only mapping type in python. It stores data in the form of key value pairs. python performs hash function operation on the key and determines the storage address of value according to the calculation result. Therefore, the dictionary is stored out of order, and the key must be hashable. Hashable means that the key must be of immutable type, such as number, string and tuple.
Dictionary is the most flexible built-in data structure type in python except list. A list is an ordered combination of objects, and a dictionary is an unordered collection of objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

increase

setdefault # adds key value pairs to the dictionary. If there are only keys, the corresponding value is none. However, if there are set key value pairs in the original dictionary, they will not be changed or overwritten.

dic = {"name": "WXQ", "age": 22, 1: [1, 2, 3]}
dic['li'] = ["a","b","c"]
print(dic)
dic.setdefault('k','v')
print(dic)  
dic.setdefault('k','v1')  
print(dic)
Output:
{'name': ['a', 'b', 'c'], 'age': 22, 1: [1, 2, 3]}
{'name': ['a', 'b', 'c'], 'age': 22, 1: [1, 2, 3], 'k': 'v'}
{'name': ['a', 'b', 'c'], 'age': 22, 1: [1, 2, 3], 'k': 'v'}

Delete

dic_pop = dic.pop("age",'nothing key Default return value') # pop deletes the key value pair according to the key and returns the corresponding value. If there is no key, it returns the default return value
print(dic_pop)
del dic["name"]  # No return value.
print(dic)
dic_pop1 = dic.popitem()  # Randomly delete a key value pair in the dictionary and return the deleted key value pair in the form of Yuanzu
print(dic_pop1)  # ('name','jin')
dic_clear = dic.clear()  # Empty dictionary
print(dic,dic_clear)    # {} None
 Output:
22
{1: [1, 2, 3]}
(1, [1, 2, 3])
{} None

change

dic = {"name":"jin","age":18,"sex":"male"}
dic2 = {"name":"alex","weight":75}
dic2.update(dic)  # Add all key value pair overrides of DIC (the same overrides, no overrides) to dic2
print(dic2)
output
{'name': 'jin', 'weight': 75, 'age': 18, 'sex': 'male'}

check

dic = {"name":"jin","age":18,"sex":"male"}
value1 = dic["name"]  # No error will be reported
print(value1)
value2 = dic.get("djffdsafg","Default return value")  # There is no return value that can be set
print(value2)
output
jin
 Default return value

other

item = dic.items()
print(item,type(item))  # dict_items([('name', 'jin'), ('sex', 'male'), ('age', 18)]) <class 'dict_items'>
This type is dict_items Type, iteratable
key = dic.keys()
print(key,type(key))  # dict_keys(['sex', 'age', 'name']) <class 'dict_keys'>
values = dic.values()
print(values,type(values))  # dict_ values(['male', 18, 'jin']) <class 'dict_ Values' > ditto
 Output:
dict_items([('name', 'jin'), ('age', 18), ('sex', 'male')]) <class 'dict_items'>
dict_keys(['name', 'age', 'sex']) <class 'dict_keys'>
dict_values(['jin', 18, 'male']) <class 'dict_values'>

Dictionary cycle

dic = {"name":"jin","age":18,"sex":"male"}
for key in dic:
    print(key)
for item in dic.items():
    print(item)
for key,value in dic.items():
    print(key,value) 
output
name
age
sex
('name', 'jin')
('age', 18)
('sex', 'male')
name jin
age 18
sex male

other

for loop: the user loops the contents of the iteratable objects in order.

msg = 'Old boy python It is the best in the country python Training institutions'
for item in msg:
    print(item)

li = ['alex','silver coins of small denominations','goddess','egon','Taibai']
for i in li:
    print(i)

dic = {'name':'Taibai','age':18,'sex':'man'}
for k,v in dic.items():
    print(k,v)

Enumerate: enumeration. For an iteratable / traversable object (such as list and string), enumerate forms it into an index sequence, which can be used to obtain the index and value at the same time.

li = ['alex','silver coins of small denominations','goddess','egon','Taibai']
for i in enumerate(li):
    print(i)
for index,name in enumerate(li,1):
    print(index,name)
for index, name in enumerate(li, 100):  # The starting position is 0 by default and can be changed
    print(index, name) 

Range: specify the range and generate the specified number.

for i in range(1,10):
    print(i)

for i in range(1,10,2):  # step
    print(i)

for i in range(10,1,-2): # Reverse step
    print(i)

Posted by calande on Sat, 18 Sep 2021 02:29:18 -0700