The road of python self-study (1) data structure

==# == variable

  • During the running of the program, the value of the variable can change
  • Variables are defined first and then used

Identifier Naming Convention

  • Composed of numbers and letters underline
  • cannot start with a number
  • System keywords cannot be used
  • View keywords:

    import keyword #Import library
    print(keyword.kwlist)

Variable naming convention:

  1. awareness of name
  2. English for exhaustion
  3. Use camel case or underscore

    num1 = num2 = 20 Uniform assignment
    num1,num2 = 10,20 Symmetric assignment

input and output

  • Output: print() comma will output a space strings=input (prompt information)
    strings is that the information entered by the user is saved

unit conversion

1bit

8bit == 1 byte

1024 bytes == 1M

1024M == 1G

1024G == 1T

Computer stores 0s and 1s

Conversion between bases

Two to ten: multiply by power and then add

Turn ten to two: add the remainder of the reciprocal division in reverse order

Eight-to-two: One-to-three-digit octal one is equivalent to three binary digits

Sixteen to two: one to four

Two-to-eight: three-one, take the low-order bit, start taking the high-order bit, and make up 0

Two to sixteen: four bits and one take


define constants

Identifiers are all uppercase

[Note] There is no strict grammar in python to define constants. By default, all uppercase is used to define constants, which are quantities whose values ​​cannot be changed during the running of the program.

Data type: use type() to get the data type

  1. int integer
  2. float float
  3. bool boolean

The case that produces false in python

False None empty string empty list[] empty dictionary{} empty tuple()

4. complex type

Both real and imaginary numbers are floating point

Function name meaning
pow power
sqrt square root
max maximum
min minimum
random random number
round rounding
floor rounding down
ceil rounding up

Type None

None is a special data type in python, None is not 0

The type of None appears most often when the function does not return a value.

Comparing None with any data type returns False

String type

  • Cannot use str as variable name
  • Strings enclosed in single and double quotes
  • Double quotes cannot be used within double quotes, and single quotes cannot be used within single quotes
  • The plus sign can be used for splicing [Note] The left and right sides are strings
  • The multiplication sign can repeat the current string
  • Strings can only be valued by key and cannot be modified by key

String subscript interception

The index value (key) starts from 0 and ends at -1

str[开始位置:结束位置:步长]  步长-1间隔取

#截取 str1[开始位置:结束位置]

#只取结束位置 默认从0开始取到结束下标

#同理只给开始位置
默认从开始位置(包含开始位置的值)取到结束位置

#不给值的时候默认取全部

#步长为-1时翻转

escaping of strings

Escape character after escape
\' '
\” ”
\n newline
\t horizontal tab

string formatting

Formatting character meaning
%s Place place for string
%d Place place for integer
%o Print in octal
%x Print in hexadecimal
%10d Integer with space
%010d Integer
with 0 %f Float The default point type placeholder is to reserve 6 decimal places
%.2f reserve 2
digits %10.2f a total of 10 digits reserve 2 digits and fill in with spaces in front of
%010.2f, same as above with 0 in front of

If there is a % in the placeholder, use %% to output one

Format the output (map) using the string's [str.format()]

print('阿郎你前女友的名字叫%(name)s,现女友姓名不详性别不详年龄%(age)d,身高不想%(hei)d' % {'hei':160,'name':'nana','age':18})
print('daishu%(name)s,daxiang%(name)s' % {'name':'sdf'})

print('{}气冲冲的从{}走出来,{}问你咋啦,袋鼠说{}非要存包'.format('daishu','chaoshi','daxiang','mmp'))

print('{2}气冲冲的从{1}走出来,{0}问你咋啦,袋鼠说{2}mmp非要存包'.format('daishu','chaoshi','daxiang'))

print('信{name}没坎坷{qianfang}一溜小平坡'.format(name='meili',qianfang='前方'))

Keyword function Keyword function
isnumeric Determine whether the string is a number replace replace
join Split the string with the specified delimiter find Find
center Fill the specified character into a new string rfind From right to left
ljust Fill upper case with left alignment
rjust Right-aligned fill lower Lowercase
lstrip Delete the specified character on the left (blank) index Find the index value of the specified string
rstrip Delete the specified character on the right (blank) title The first letter of each word is capitalized
eval Calculates the expression as the result strip Deletes the specified characters on both sides (blank)

str2 = '12345'

print(str2.isnumeric())

str1 = 'hhhh'

print(str1.center(10,*))  //***hhhh***


#字符串前加r 防止特殊字符转义

str3 = r'c: \user\asdsa''

type of data

List type (an ordered collection of data)

Definition: Use [] to define a list, the values ​​in the list can be

1. 定义一个空列表[]
2. 下标可以读取列标识 classList[0]
3. 也有同字符串的切片截取 eg:classList[:3]
4. 可以通过下标修改值,但不可以越界
5. 列表可以对称赋值 [num1,num2] = [num2,num1]
6. 列表的删改查  del列表元素,对应下标赋值

List function name works as
len list, string length
count counts the number of times a value appears in the list
extend appends the value in the list
insert inserts the value at the specified position
pop pops the last element
of the list remove matches the first element in the list to the specified element remove
reverse reverse the original list
clear clear the original list
append list add elements
sort ascending

myList = ['a','b','c']
#列表中追加值
print(myList.extend(['f','g']))

print(myList.insert('w','t'))  #在下标为2的位置插入w,t
print(myList)
结果:['a','b','w','t',c']

In python, addresses are stored not by variable names but by values

num = 5
num2 = 5
print(id(num))
print(id(num2))   #以值来存储  所以指向一样
num2 = 10
print(id(num))
print(id(num2))    #num2的值修改后  指向发生改变

Shallow copy (pointer is an address)

myList = [1,3,4,6]
myList2 = myList
myList2[0] = 'a'
print(id(myList))
print(id(myList2))
print(myList)
print(myList2)

#结果:
43484872
43484872
['a', 3, 4, 6]
['a', 3, 4, 6]

deep copy (literally true copy)

myList3 = ['a','b','c']
myList4 = myList3.copy()
myList4[0] = '1'
print(id(myList3))
print(id(myList4))
print(myList3)
print(myList4)

结果:
43615944
43616136
['a', 'b', 'c']
['1', 'b', 'c']

copy.copy in the module only copies one layer, also called shallow copy

myList = ['1','a','f']
myList2 = copy.copy(myList)
myList[0] = 'd'
print(id(myList))
print(id(myList2))
print(myList)
print(myList2)

结果:
43353800
43353992
['d', 'a', 'f']
['1', 'a', 'f']

myList = ['1','a','f',['df','fg']]
myList2 = copy.copy(myList)
myList[3][0] = 'd'
print(id(myList))
print(id(myList2))
print(myList)
print(myList2)

结果:
36079496
36080776
['1', 'a', 'f', ['d', 'fg']]
['1', 'a', 'f', ['d', 'fg']]

deep copy

myList = ['1','a','f',['df','fg']]
myList2 = copy.deepcopy(myList)
myList[3][0] = 'wwww'
print(myList)
print(myList2)

结果:
['1', 'a', 'f', ['wwww', 'fg']]
['1', 'a', 'f', ['df', 'fg']]

[Note] In Python, the assignment of objects is carried out by object reference (memory address) transfer

[Note] A shallow copy will create a new object, but for the elements in the object, the shallow copy will only use the reference (memory address) of the original element.


To sum up, when we use the following operations, it will produce the effect of shallow copy:

  • Use slice[:] operations
  • Use factory functions (like list/dir/set)
  • Use the copy() function from the copy module

==Usage==

  1. The assignment of objects in Python is to pass the memory address (change a full change, the id is the same)
  2. Using copy(), the object is not nested deep copy (change which one changes), if the list is nested, it is a shallow copy (change a full change)
  3. Using copy.copy(), you can make a shallow copy of the object, which copies the object, but still uses the original reference (memory address transfer) for the elements in the object.
  4. If you need to copy a container object, and all the elements in it (including the child elements of the element), you can use copy.deepcopy() to make a deep copy
  5. Non-container types (such as numbers, strings, and other 'atomic' types of objects) are not copied
  6. If the tuple variable contains only atomic type objects, you cannot deep copy

tuple

  1. Tuple values ​​cannot be modified
  2. When the value is a list, the value in the list can be modified
  3. It can be based on subscript values ​​or subscript slices, similar to strings and lists
  4. Also + and * function the same
  5. del cannot delete the specified subscript value and can directly delete all
  6. in can determine whether a value exists in a tuple

collection set

  1. Cannot use {} to define an empty set use ==set2 = set()== to define an empty set
  2. Collection elements do not repeat
  3. + and * cannot be used

    myList = [1,3,5,7,7]
    print(set(myList))

    Result: [1, 3, 5, 7]

    set1 = {‘a’,’b’,’c’}
    set2 = {‘d’,’e’,’a’,’w’}

    difference

    print(set1 - set2)

    union

    print(set1 | set2)

    intersection

    print(set1 & set2)

    not coexist

    print(set1 ^ set2)

dictionary

  1. The dictionary type is formed in the form of key->value and the search speed is very fast
  2. definition{}

    dict1 = {‘name’:’aa’,’age’:1}
    classList = {‘bb’:90,’ww’:92}

  3. Subscripts are composed of strings and integers

  4. The key value appears in pairs, the subscript is unique


    Query classList['name'] by subscript
    Modify
    classList['name'] = 'qwe'
    Delete
    del classList['name']
    Find
    print(classList.get('aa')) #Subscript exists return value does not exist display None
    classList.keys() #Remove all keys in the current dictionary data
    classList.values() #Remove all values ​​in the current dictionary
    classList.pop(87) #Pop up value by key

    The function of the dictionary function
    update is to merge the same key of the dictionary, overwrite the
    keys, take out all the key
    values, take out all the values ​​in the current dictionary
    pop pop the value by key
    get query

data type conversion

str1 = str(10.45) 转字符串
str2 = int('10')  转整型
str3 = float('10') 转浮点型
list() 转成列表

Conversion function function
bool Convert to boolean type
int Convert to integer type
str Convert to character type
float Convert to floating point type
dict Convert to dictionary type
set Convert to collection type
list Convert to list type
tuple Convert to tuple type

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324734487&siteId=291194637