current position:Home>Python Foundation: data structure summary

Python Foundation: data structure summary

2022-01-30 15:36:47 chaoyu

list

Definition of list

A list is an ordered set , No fixed size , Can save any number of any type of Python object , The grammar is [ Elements 1, Elements 2, ..., Elements n].

  • The key point is 「 brackets []」 and 「 comma ,」
  • brackets Tie all the elements together
  • comma Separate each element one by one

List creation

  • Normal list
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x, type(x))
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] <class 'list'>

x = [2, 3, 4, 5, 6, 7]
print(x, type(x))
# [2, 3, 4, 5, 6, 7] <class 'list'>
 Copy code 
  • range() Create a list of
x = list(range(10))
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>

x = list(range(1, 11, 2))
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>

x = list(range(10, 1, -2))
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>
 Copy code 
  • Inferentially create a list
x = [0] * 5
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>

x = [0 for i in range(5)]
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>

x = [i for i in range(10)]
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>

x = [i for i in range(1, 10, 2)]
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>

x = [i for i in range(10, 1, -2)]
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>

x = [i ** 2 for i in range(1, 10)]
print(x, type(x))
# [1, 4, 9, 16, 25, 36, 49, 64, 81] <class 'list'>

x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x, type(x))

# [3, 9, 15, 21, 27, 33, 39,
 Copy code 

because list The element of can be any object , So what's in the list is a pointer to the object . Even save a simple [1,2,3], Also have 3 A pointer and 3 An integer object . x = [a] * 4 In operation , Just create 4 A point list References to , So once a change ,x in 4 individual a It's going to change .

  • Create a mixed list
mix = [1, 'lsgo', 3.14, [1, 2, 3]]
print(mix, type(mix))  
# [1, 'lsgo', 3.14, [1, 2, 3]] <class 'list'>
 Copy code 
  • Create an empty list
empty = []
print(empty, type(empty))  # [] <class 'list'>
 Copy code 

Add elements to the list

Lists don't look like tuples , The contents of the list can be changed (mutable), So add (append, extend)、 Insert (insert)、 Delete (remove, pop) These operations are available

  • list.append(obj) Add a new object at the end of the list , Accept only one parameter , Parameters can be any data type , The appended element is in list The original structure type is maintained in
  • list.extend(seq) Appends multiple values from another sequence at once at the end of the list ( Extend the original list with the new list )

Strictly speaking append It's an addition , Add a whole thing to the list , and extend It 's an extension , Add all the elements of a thing to the list

  • list.insert(index, obj) In the number index Position insert obj

Delete the elements in the list

  • list.remove(obj) Removes the first match of a value in the list
  • list.pop([index=-1]) Removes an element from the list ( Default last element ), And returns the value of that element
  • del var1[, var2 ……] Delete single or multiple objects
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
del x[0:2]
print(x)  # ['Wednesday', 'Thursday', 'Friday']
 Copy code 

Get the elements in the list

  • By the index value of the element , Get a single element from a list , Be careful , The list index value is from 0 At the beginning .
  • By specifying the index as -1, Allowing Python Returns the last list element , Indexes -2 Returns the second to last list element , And so on

The general way to write slices is start : stop : step

  • "start :" With step by 1 ( Default ) From number start Slice to the end of the list .
  • ": stop" With step by 1 ( Default ) Number from the head of the list stop section
  • "start : stop" With step by 1 ( Default ) From number start To number stop section
  • "start : stop : step" Concrete step From number start To number stop section . Pay attention to the last step Set to -1, It is equivalent to arranging the list in reverse
  • " : " Copy all elements in the list ( Shallow copy )

Common operators for lists

  • The equal sign operator :==
  • Join operators +
  • Repeat operator *
  • Membership operators in、not in

Other methods of listing

  • list.count(obj) Count the number of times an element appears in a list
list1 = [123, 456] * 3
print(list1)  # [123, 456, 123, 456, 123, 456]
num = list1.count(123)
print(num)  # 3
 Copy code 
  • list.index(x[, start[, end]]) Find the index position of the first match of a value in the list
list1 = [123, 456] * 5
print(list1.index(123))  # 0
print(list1.index(123, 1))  # 2
print(list1.index(123, 3, 7))  # 4
 Copy code 
  • list.reverse() Reverse list of elements
x = [123, 456, 789]
x.reverse()
print(x)  # [789, 456, 123]
 Copy code 
  • list.sort(key=None, reverse=False) Sort the original list

key -- It's basically a comparison element , There is only one parameter , The parameters of the specific function are taken from the iterable object , Specifies an element in an iterable object to sort . reverse -- Sort rule ,reverse = True Descending , reverse = False Ascending ( Default ). The method does not return a value , But it sorts the objects in the list

x = [123, 456, 789, 213]
x.sort()
print(x)
# [123, 213, 456, 789]

x.sort(reverse=True)
print(x)
# [789, 456, 213, 123]


#  Get the second element of the list 
def takeSecond(elem):
    return elem[1]


x = [(2, 2), (3, 4), (4, 1), (1, 3)]
x.sort(key=takeSecond)
print(x)
# [(4, 1), (2, 2), (1, 3), (3, 4)]

x.sort(key=lambda a: a[0])
print(x)
# [(1, 3), (2, 2), (3, 4), (4, 1)]
 Copy code 

Tuples

grammar :( Elements 1, Elements 2, ..., Elements n)

  • Parentheses bind all elements together
  • Commas separate each element one by one

Create and access a tuple

  • Python A tuple of is similar to a list , The difference is tuple You can't modify it after it's created , String like .
  • Tuples use braces , Use square brackets for lists .
  • Tuples are similar to lists , It's also indexed by integers (indexing) And slicing (slicing)
t1 = (1, 10.31, 'python')
t2 = 1, 10.31, 'python'
print(t1, type(t1))
# (1, 10.31, 'python') <class 'tuple'>

print(t2, type(t2))
# (1, 10.31, 'python') <class 'tuple'>

tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple1[1])  # 2
print(tuple1[5:])  # (6, 7, 8)
print(tuple1[:5])  # (1, 2, 3, 4, 5)
tuple2 = tuple1[:]
print(tuple2)  # (1, 2, 3, 4, 5, 6, 7, 8)
 Copy code 
  • Create tuples with parentheses (), You can also use nothing , For readability , Suggest or use ().
  • When a tuple contains only one element , You need to add a comma after the element , Otherwise parentheses will be used as operators .

【 Example 】 Create a two-dimensional tuple

x = (1, 10.31, 'python'), ('data', 11)
print(x)
# ((1, 10.31, 'python'), ('data', 11))

print(x[0])
# (1, 10.31, 'python')
print(x[0][0], x[0][1], x[0][2])
# 1 10.31 python

print(x[0][0:2])
# (1, 10.31)
 Copy code 

Update and delete a tuple

Tuples have immutable (immutable) The nature of , So you can't assign values to elements of tuples directly , But as long as the elements in the tuple can be changed (mutable), So we can change its elements directly , Notice that this is different from assigning its elements

t1 = (1, 2, 3, [4, 5, 6])
print(t1)  # (1, 2, 3, [4, 5, 6])

t1[3][0] = 9
print(t1)  # (1, 2, 3, [9, 5, 6])
 Copy code 

Tuple related operators

  • The equal sign operator :==
  • Join operators : +
  • Repeat operator : *
  • Membership operators : in、not in

There are two ways to splice tuples , use 「 plus +」 and 「 Multiplication sign *」, The former is spliced head to tail , The latter copies the splice

Built-in methods

Tuple size and content cannot be changed , So only count and index The two methods

Decompress tuples

  • decompression (unpack) One dimensional tuples ( There are several elements, and the left bracket defines several variables )
t = (1, 10.31, 'python')
(a, b, c) = t
print(a, b, c)
# 1 10.31 python
 Copy code 
  • Decompress the two-dimensional tuple ( Define variables according to the tuple structure in tuples )
t = (1, 10.31, ('OK', 'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
# 1 10.31 OK python
 Copy code 
  • If you only want a few elements of a tuple , Use wildcards 「*」, English name wildcard, Representing one or more elements in a computer language . The following example is to throw multiple elements to rest Variable
t = 1, 2, 3, 4, 5
a, b, *rest, c = t
print(a, b, c)  # 1 2 5
print(rest)  # [3, 4]
 Copy code 
  • If you don't care rest Variable , Then use wildcards 「*」 Underline 「_」
t = 1, 2, 3, 4, 5
a, b, *_ = t
print(a, b)  # 1 2
 Copy code 

character string

Definition of string

Python A string in is defined as a set of characters between quotation marks . Python Support the use of paired Single quotation marks or Double quotes

  • Python Common escape characters
Escape character describe
\\ Backslash notation
' Single quotation marks
" Double quotes
\n Line break
\t Horizontal tabs (TAB)
\r enter

The original string only needs to be preceded by an English letter r that will do

print(r'C:\Program Files\Intel\Wifi\Help')  
# C:\Program Files\Intel\Wifi\Help
 Copy code 

Three quotes allow a string to span multiple lines , String can contain line breaks 、 Tabs and other special characters

Slicing and splicing of strings

  • Similar to tuples, they are immutable
  • from 0 Start ( and Java equally )
  • Slices are usually written as start:end This form , Include 「start Indexes 」 Corresponding elements , barring 「end Indexes 」 Corresponding elements .
  • Index values can be positive or negative , Is indexing from 0 Start , From left to right ; Negative index from -1 Start , From right to left . When using a negative index , Will start counting from the last element . The position number of the last element is -1.
str1 = 'I Love LsgoGroup'
print(str1[:6])  # I Love
print(str1[5])  # e
print(str1[:6] + "  The inserted string  " + str1[6:])  
# I Love  The inserted string  LsgoGroup

s = 'Python'
print(s)  # Python
print(s[2:4])  # th
print(s[-5:-2])  # yth
print(s[2])  # t
print(s[-1])  # n
 Copy code 

Common built-in methods for Strings

  • capitalize() Convert the first character of the string to uppercase
  • lower() Convert all uppercase characters in the string to lowercase .
  • upper() Convert the lowercase letters in the string to uppercase .
  • swapcase() Convert upper case to lower case in string , Lower case to upper case .
  • count(str, beg= 0,end=len(string)) return str stay string The number of times it's inside , If beg perhaps end If specified, return to the specified range str Number of occurrences
  • endswith(suffix, beg=0, end=len(string)) Check whether the string specifies a substring suffix end , If it is , return True, Otherwise return to False. If beg and end Specify the value , Check... Within the specified range .
  • startswith(substr, beg=0,end=len(string)) Check whether the string specifies a substring substr start , If it is , return True, Otherwise return to False. If beg and end Specify the value , Check... Within the specified range
  • find(str, beg=0, end=len(string)) testing str Whether to include in the string , If you specify a range beg and end, Then check whether it is included in the specified range , If you include , Returns the starting index value , Otherwise return to -1.
  • rfind(str, beg=0,end=len(string)) Be similar to find() function , Just search from the right
  • isnumeric() If the string contains only numeric characters , Then return to True, Otherwise return to False
  • ljust(width[, fillchar]) Returns an original string left aligned , And use fillchar( Default space ) Fill to length width New string of .
  • rjust(width[, fillchar]) Returns an original string to the right , And use fillchar( Default space ) Fill to length width New string of
  • lstrip([chars]) Truncates the space to the left of the string or specifies the character .
  • rstrip([chars]) Delete the space at the end of the string or the specified character .
  • strip([chars]) Execute... On a string lstrip() and rstrip()
  • partition(sub) Find the substring sub, Divide the string into a triple (pre_sub,sub,fol_sub), If the string does not contain sub Then return to (' Original string ','','').
  • rpartition(sub) Be similar to partition() Method , Just search from the right
  • replace(old, new [, max]) hold In the string old Replace with new, If max Appoint , The substitution does not exceed max Time
  • split(str="", num) Without parameters, the default is to slice string with space as separator , If num Parameters are set , Only separate num Substring , Returns the list of concatenated substrings after slicing
  • splitlines([keepends]) Follow the line ('\r', '\r\n', \n') Separate , Returns a list of rows as elements , If parameters keepends by False, Does not contain line breaks , If True, Keep the newline
  • aketrans(intab, outtab) Create a conversion table for character mapping , The first parameter is the string , Indicates the character to be converted , The second parameter is also the target of string representation transformation .
  • translate(table, deletechars="") According to the parameters table The table given , Convert string characters , Put the filtered characters in deletechars Parameters in

String formatting

  • format Format function
str8 = "{0} Love {1}".format('I', 'Lsgogroup')  #  Positional arguments 
print(str8)  # I Love Lsgogroup

str8 = "{a} Love {b}".format(a='I', b='Lsgogroup')  #  Key parameters 
print(str8)  # I Love Lsgogroup

str8 = "{0} Love {b}".format('I', b='Lsgogroup')  #  The position parameter should precede the keyword parameter 
print(str8)  # I Love Lsgogroup

str8 = '{0:.2f}{1}'.format(27.658, 'GB')  #  Keep two decimal places 
print(str8)  # 27.66GB
 Copy code 
  • Python String formatting symbols
operator Number describe
%c Format characters and their ASCII code
%s Formatted string , use str() Method to handle objects
%r Formatted string , use rper() Method to handle objects
%d Formatted integer
%o Format an unsigned octal number
%x Formats unsigned hexadecimal Numbers
%X Formats unsigned hexadecimal Numbers ( Capitalization )
%f Formatted floating point number , Precision after the decimal point can be specified
%e Scientific notation for formatting floating - point Numbers
%E Work with %e, Scientific notation for formatting floating - point Numbers
%g Use... Depending on the size of the value %f or %e
%G Work with %g, Use... Depending on the size of the value %f or %E
  • Formatting operator helper
Symbol function
m.n m Is the minimum overall width of the display ,n It's the number of decimal places ( If available )
- Used for left alignment
+ Show a plus sign before a positive number ( + )
# Show zero before octal number ('0'), Show... In front of hex '0x' perhaps '0X'( It depends on what you use 'x' still 'X')
0 Fill in the front of the displayed number '0' Not the default space

Dictionaries

Variable type and immutable type

  • A sequence is indexed by consecutive integers , The difference is , Dictionary with " keyword " Index , Keywords can be any immutable type , It's usually a string or a number .
  • The dictionary is Python The only one Mapping type , character string 、 Tuples 、 Lists are of the sequence type

How to quickly judge a data type X Is it a variable type ? The two methods

  1. Trouble method : use id(X) function , Yes X Do something , Compare before and after operation id, If it's not the same , be X immutable , If the same , be X variable
  2. Easy way : use hash(X), As long as there is no error , prove X Can be hashed , That is immutable , Conversely, it cannot be hashed , Can change

Dictionary definition

Dictionaries Is chaotic key : value (key:value) The collection , The keys have to be different from each other ( In the same dictionary )

  • dict The order of internal storage and key It doesn't matter in what order .
  • dict Fast search and insertion , Not as key To increase by , But it takes a lot of memory

Dictionaries The definition syntax is { Elements 1, Elements 2, ..., Elements n}

  • Each of these elements is a 「 Key value pair 」-- key : value (key:value)
  • The key point is 「 Curly braces {}」,「 comma ,」 and 「 The colon :」
  • Curly braces -- Tie all the elements together
  • comma -- Separate each key value pair
  • The colon -- Separate keys from values

Creating and accessing Dictionaries

brand = [' Lining ', ' Nike ', ' Adidas ']
slogan = [' Anything is possible ', 'Just do it', 'Impossible is nothing']
print(' Nike's slogan is :', slogan[brand.index(' Nike ')])  
#  Nike's slogan is : Just do it

dic = {' Lining ': ' Anything is possible ', ' Nike ': 'Just do it', ' Adidas ': 'Impossible is nothing'}
print(' Nike's slogan is :', dic[' Nike '])  
#  Nike's slogan is : Just do it
 Copy code 

Use a string or numeric value as key To create a dictionary

dic1 = {1: 'one', 2: 'two', 3: 'three'}
print(dic1)  # {1: 'one', 2: 'two', 3: 'three'}
print(dic1[1])  # one
print(dic1[4])  # KeyError: 4
 Copy code 

If the key taken does not exist in the dictionary , Will report an error directly KeyError

  • dict() Create an empty dictionary

adopt key Put the data directly into the dictionary , But a key There's only one value, Many to one key Put in value, The value in the back will flush out the value in the front

dic = dict()
dic['a'] = 1
dic['b'] = 2
dic['c'] = 3

print(dic)
# {'a': 1, 'b': 2, 'c': 3}

dic['a'] = 11
print(dic)
# {'a': 11, 'b': 2, 'c': 3}

dic['d'] = 4
print(dic)
# {'a': 11, 'b': 2, 'c': 3, 'd': 4}
 Copy code 
  • dict(mapping)
dic1 = dict([('apple', 4139), ('peach', 4127), ('cherry', 4098)])
print(dic1)  # {'cherry': 4098, 'apple': 4139, 'peach': 4127}

dic2 = dict((('apple', 4139), ('peach', 4127), ('cherry', 4098)))
print(dic2)  # {'peach': 4127, 'cherry': 4098, 'apple': 4139}
 Copy code 
  • dict(**kwargs)
dic = dict(name='Tom', age=10)
print(dic)  # {'name': 'Tom', 'age': 10}
print(type(dic))  # <class 'dict'>
 Copy code 

Built in method of Dictionary

  • dict.fromkeys(seq[, value]) Used to create a new dictionary , In sequence seq The middle element is the key of the dictionary ,value Is the initial value of all keys in the dictionary
  • dict.keys() Returns an iteratable object , have access to list() To convert to list , The list is all the keys in the dictionary
  • dict.values() Returns an iterator , have access to list() To convert to list , The list is all the values in the dictionary
  • dict.items() Return traversable as a list ( key , value ) Tuple array
  • dict.get(key, default=None) Returns the value of the specified key , If the value is not in the dictionary, return the default value
  • dict.setdefault(key, default=None) and get() Method similar , If the key does not exist in the dictionary , The key will be added and the value will be set to the default value
dic = {'Name': 'Lsgogroup', 'Age': 7}
print("Age  Key value is  : %s" % dic.setdefault('Age', None))  # Age  Key value is  : 7
print("Sex  Key value is  : %s" % dic.setdefault('Sex', None))  # Sex  Key value is  : None
print(dic)  
# {'Age': 7, 'Name': 'Lsgogroup', 'Sex': None}
 Copy code 
  • key in dict in The operator is used to determine whether the key exists in the dictionary , If the key is in the dictionary dict Back in true, Otherwise return to false. and not in The operator is just the opposite , If the key is in the dictionary dict Back in false, Otherwise return to true
  • dict.pop(key[,default]) Delete dictionary given key key The corresponding value , The return value is the deleted value .key Value must be given . if key non-existent , Then return to default value .
  • del dict[key] Delete dictionary given key key The corresponding value
  • dict.popitem() Randomly return and delete a pair of keys and values in the dictionary , If the dictionary is empty , This method is called , Just report KeyError abnormal
  • dict.clear() Used to delete all elements in the dictionary
  • dict.copy() Returns a shallow copy of a dictionary
  • dict.update(dict2) Put the dictionary parameter dict2 Of key:value Yes Update to dictionary dict in

aggregate

Python in set And dict similar , It's also a group. key Set , But no storage. value. because key Can't repeat , therefore , stay set in , No repeat key.

Be careful ,key Is immutable type , The hash value

characteristic disorder (unordered) And the only

num = {}
print(type(num))  # <class 'dict'>
num = {1, 2, 3, 4}
print(type(num))  # <class 'set'>
 Copy code 

Set creation

  • Create objects before adding elements
  • When creating an empty collection, you can only use s = set(), because s = {} An empty dictionary is created
  • Just enclose a bunch of elements in curly braces { Elements 1, Elements 2, ..., Elements n}
  • Repeating elements in set Will be automatically filtered
  • Use set(value) Factory function , Convert a list or tuple into a set

because set It stores unordered sets , So we can't index a collection or slice it (slice) operation , There are no keys (keys) Can be used to get the value of the element in the collection , But you can determine whether an element is in the collection

Access the values in the collection

  • have access to len() The built-in function gets the size of the set
s = set(['Google', 'Baidu', 'Taobao'])
print(len(s))  # 3
 Copy code 
  • have access to for Read out the data in the set one by one
s = set(['Google', 'Baidu', 'Taobao'])
for item in s:
    print(item)
    
# Baidu
# Google
# Taobao
 Copy code 
  • Can pass in or not in Determine whether an element already exists in the collection
s = set(['Google', 'Baidu', 'Taobao'])
print('Taobao' in s)  # True
print('Facebook' not in s)  # True
 Copy code 

Built in methods for collections

  • set.add(elmnt) Used to add elements to a collection , If the added element already exists in the collection , Do nothing
  • set.update(set) Used to modify the current collection , You can add new elements or collections to the current collection , If the added element already exists in the collection , The element will only appear once , Repeated will ignore
  • set.remove(item) Used to remove a specified element from a collection . If the element does not exist , An error will occur
  • set.discard(value) Used to remove the specified collection element .remove() Method to remove a nonexistent element will cause an error , and discard() No way
  • set.pop() Used to randomly remove an element

because set Is a collection of unordered and non repeating elements , So two or more set Can do set operations in the mathematical sense

  • set.intersection(set1, set2) Returns the intersection of two sets .
  • set1 & set2 Returns the intersection of two sets .
  • set.intersection_update(set1, set2) intersection , Remove non overlapping elements from the original collection
  • set.union(set1, set2) Returns the union of two sets .
  • set1 | set2 Returns the union of two sets
  • set.difference(set) Returns the difference set of a set .
  • set1 - set2 Returns the difference set of a set .
  • set.difference_update(set) Difference sets of sets , Remove elements directly from the original collection , no return value
  • set.symmetric_difference(set) Returns the XOR of the set .
  • set1 ^ set2 Returns the XOR of the set .
  • set.symmetric_difference_update(set) Remove the same elements from the current collection in another specified collection , And insert different elements of another specified collection into the current collection
  • set.issubset(set) Determine whether the set is contained by other sets , If so, return True, Otherwise return to False.
  • set1 <= set2 Determine whether the set is contained by other sets ,- If so, return True, Otherwise return to False
  • set.issuperset(set) Used to determine whether the set contains - Other sets , If so, return True, Otherwise return to - False.
  • set1 >= set2 Determine whether the set contains other sets , If so, return True, Otherwise return to False
  • set.isdisjoint(set) Used to determine whether two sets are disjoint , If it's a return True, Otherwise return to False

The transformation of sets

se = set(range(4))
li = list(se)
tu = tuple(se)

print(se, type(se))  # {0, 1, 2, 3} <class 'set'>
print(li, type(li))  # [0, 1, 2, 3] <class 'list'>
print(tu, type(tu))  # (0, 1, 2, 3) <class 'tuple'>
 Copy code 

Immutable set

Python Provides an implementation version of a collection that cannot be changed , That is, you can't add or delete elements , Type name frozenset. It should be noted that frozenset You can still do set operations , It's just that you can't use it with update Methods .

  • frozenset([iterable]) Returns a frozen collection , After freezing, no more elements can be added or removed from the collection .
a = frozenset(range(10))  #  Generates a new immutable set 
print(a)  
# frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})

b = frozenset('lsgogroup')
print(b)  
# frozenset({'g', 's', 'p', 'r', 'u', 'o', 'l'})
 Copy code 

Sequence

stay Python in , Sequence types include strings 、 list 、 Tuples 、 Collections and dictionaries , These sequences support some common operations , But what's more special is , Indexes are not supported in collections and dictionaries 、 section 、 Add and multiply operations

Built in functions for sequences

  • list(sub) Convert an iteratable object to a list
a = list()
print(a)  # []

b = 'I Love LsgoGroup'
b = list(b)
print(b)  
# ['I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p']

c = (1, 1, 2, 3, 5, 8)
c = list(c)
print(c)  # [1, 1, 2, 3, 5, 8]
 Copy code 
  • tuple(sub) Convert an iteratable object to a tuple
a = tuple()
print(a)  # ()

b = 'I Love LsgoGroup'
b = tuple(b)
print(b)  
# ('I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p')

c = [1, 1, 2, 3, 5, 8]
c = tuple(c)
print(c)  # (1, 1, 2, 3, 5, 8)
 Copy code 
  • str(obj) hold obj Object to string
a = 123
a = str(a)
print(a)  # 123
 Copy code 
  • len(s) Returns the object ( character 、 list 、 Tuples etc. ) Length or number of elements
    • s -- object
a = list()
print(len(a))  # 0

b = ('I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p')
print(len(b))  # 16

c = 'I Love LsgoGroup'
print(len(c))  # 16
 Copy code 
  • max(sub) Returns the maximum value in a sequence or parameter set
print(max(1, 2, 3, 4, 5))  # 5
print(max([-8, 99, 3, 7, 83]))  # 99
print(max('IloveLsgoGroup'))  # v
 Copy code 
  • min(sub) Returns the minimum value in a sequence or parameter set
print(min(1, 2, 3, 4, 5))  # 1
print(min([-8, 99, 3, 7, 83]))  # -8
print(min('IloveLsgoGroup'))  # G
 Copy code 
  • sum(iterable[, start=0]) Return sequence iterable With optional parameters start The sum of
print(sum([1, 3, 5, 7, 9]))  # 25
print(sum([1, 3, 5, 7, 9], 10))  # 35
print(sum((1, 3, 5, 7, 9)))  # 25
print(sum((1, 3, 5, 7, 9), 20))  # 45
 Copy code 
  • sorted(iterable, key=None, reverse=False) Sort all iteratable objects
    • iterable -- Iteratable object .
    • key -- It's basically a comparison element , There is only one parameter , The parameters of the specific function are taken from the iterable object , Specifies an element in an iterable object to sort .
    • reverse -- Sort rule ,reverse = True Descending , reverse = False Ascending ( Default ).
    • Return to the reordered list
x = [-8, 99, 3, 7, 83]
print(sorted(x))  # [-8, 3, 7, 83, 99]
print(sorted(x, reverse=True))  # [99, 83, 7, 3, -8]

t = ({"age": 20, "name": "a"}, {"age": 25, "name": "b"}, {"age": 10, "name": "c"})
x = sorted(t, key=lambda a: a["age"])
print(x)
# [{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]
 Copy code 
  • reversed(seq) Function returns an inverted iterator
    • seq -- The sequence to convert , It can be tuple, string, list or range
    s = 'lsgogroup'
      x = reversed(s)
      print(type(x))  # <class 'reversed'>
      print(x)  # <reversed object at 0x000002507E8EC2C8>
      print(list(x))
      # ['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l']
    
      t = ('l', 's', 'g', 'o', 'g', 'r', 'o', 'u', 'p')
      print(list(reversed(t)))
      # ['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l']
    
      r = range(5, 9)
      print(list(reversed(r)))
      # [8, 7, 6, 5]
    
      x = [-8, 99, 3, 7, 83]
      print(list(reversed(x)))
      # [83, 7, 3, 99, -8]
     Copy code 
  • enumerate(sequence, [start=0]) For traversing a data object ( As listing 、 Tuples or strings ) Combined into an index sequence , List both data and data index , Generally used in for Cycle of
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
a = list(enumerate(seasons))
print(a)  
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

b = list(enumerate(seasons, 1))
print(b)  
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

for i, element in a:
    print('{0},{1}'.format(i, element))
# 0,Spring
# 1,Summer
# 2,Fall
# 3,Winter
 Copy code 
  • zip(iter1 [,iter2 [...]])
    • Used to take iteratable objects as parameters , Package the corresponding elements in the object into tuples , And then return the objects made up of these tuples , The advantage is that it saves a lot of memory .
    • have access to list() Convert to output list .
    • If the number of elements in each iterator is inconsistent , Returns a list of the same length as the shortest object , utilize * The operator , Tuples can be unzipped into lists .
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]

zipped = zip(a, b)
print(zipped)  # <zip object at 0x000000C5D89EDD88>
print(list(zipped))  # [(1, 4), (2, 5), (3, 6)]
zipped = zip(a, c)
print(list(zipped))  # [(1, 4), (2, 5), (3, 6)]

a1, a2 = zip(*zip(a, b))
print(list(a1))  # [1, 2, 3]
print(list(a2))  # [4, 5, 6]
 Copy code 

copyright notice
author[chaoyu],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301536449738.html

Random recommended