The list of
Definition of a list
Lists are ordered collections that have no fixed size and can hold any number of Python objects of any type. The syntax is [element 1, element 2,… element n].
- The key points are “brackets []” and “comma,”
- Brackets bind all the elements together
- The comma separates each element one by one
List creation
- General 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 the code
- Range () creates a list
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 the code
- Create lists by derivation
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 the code
Since the elements of a list can be any object, all that is held in a list are Pointers to objects. Even if you save a simple [1,2,3], there are three Pointers and three integer objects. The x = [a] * 4 operation creates only four references to the list, so whenever a changes, the four As in x change with it.
- 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 the code
- Create an empty list
empty = []
print(empty, type(empty)) # [] <class 'list'>
Copy the code
Add elements to the list
Lists, unlike tuples, are mutable, so operations such as append (extend), insert (insert), and delete (pop) are available
list.append(obj)
Add a new object to the end of the list that takes only one argument, which can be of any data type. The element appended to the list retains its original structural typelist.extend(seq)
Append multiple values from another sequence at the end of the list at once (extending the original list with the new list)
Strictly speaking, append is an append that adds an item to the list as a whole, while extend is an extension that adds all elements of an item to the list
- List. Insert (index, obj) Insert obj at index
Remove elements from 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 (the last element by default) and returns the value of that element
- Del var1, var2 […] Delete one or more objects
x = ['Monday'.'Tuesday'.'Wednesday'.'Thursday'.'Friday']
del x[0:2]
print(x) # ['Wednesday', 'Thursday', 'Friday']
Copy the code
Gets the elements in the list
- Retrieves a single element from the list by its index value, which starts at 0.
- By specifying an index of -1, Python can return the last list element, index -2 returns the penultimate list element, and so on
The common way to write a slice is start: stop: step
- “Start :” Slices from the number start to the end of the list with step 1 (default).
- “: stop” slices from the head of the list to stop with step 1 (default)
- “Start: stop” slices from start to stop with step as 1 (default)
- “Start: stop: step” the specific step is sliced from start to stop.Note that setting step to -1 at the end is equivalent to reversing the list
- Copy all elements in the list (shallow copy)
Common operators for lists
- The equal operator: ==
- The join operator +
- The repeat operator *
- The membership operators are in, not in
Other methods of lists
- List.count (obj) Counts the number of occurrences of an element in a list
list1 = [123.456] * 3
print(list1) # [123, 456, 123, 456, 123, 456]
num = list1.count(123)
print(num) # 3
Copy the code
- List.index (x[, start[, end]]) finds the index position of the first match for 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 the code
- List.reverse () reverses the elements in the list
x = [123.456.789]
x.reverse()
print(x) # [789, 456, 123]
Copy the code
- List.sort (key=None, reverse=False) sorts the original list
Key — A comparison element that takes only one argument. The argument to the function is taken from the iterable, and an element in the iterable is specified for sorting. Reverse — Collation, reverse = True descending, reverse = False ascending (default). This method returns no value, but 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 the code
tuples
Syntax :(element 1, element 2… Element, n)
- The parentheses bind all the elements together
- The comma separates each element one by one
Create and access a tuple
- Python tuples are similar to lists, except that tuples cannot be modified after they are created, similar to strings.
- Tuples use parentheses and lists use square brackets.
- Tuples, like lists, are indexed and slicing with integers
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 the code
- Tuples can be created using parentheses () or nothing at all, but () is recommended for readability.
- When a tuple contains only one element, you need to add a comma after the element, otherwise the 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])
10.31 the python # 1
print(x[0] [0:2])
# (1, 10.31)
Copy the code
Update and delete a tuple
Tuples are immutable, and therefore cannot be directly assigned to elements of tuples, but it is possible to change elements of tuples as long as they are mutable. Note that this is not like assigning elements to them
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 the code
Tuple related operators
- The equal operator: ==
- Join operator: +
- Repeat operator: *
- Membership operators: in, not in
Tuple concatenation has two ways, using “plus +” and “times *”, the former head and tail concatenation, the latter copy concatenation
Built-in methods
Tuple size and content cannot be changed, so there are only count and index methods
Unpack the tuple
- Unpack a one-dimensional tuple (there are several elements and the left parentheses define several variables)
t = (1.10.31.'python')
(a, b, c) = t
print(a, b, c)
10.31 the python # 1
Copy the code
- Unpack a two-dimensional tuple (define variables according to the tuple structure in the tuple)
t = (1.10.31, ('OK'.'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
# 1 10.31 OK python
Copy the code
- If you want only a few elements of a tuple, use the “*” character, called wildcard, for one or more elements in computer language. The following example is to throw multiple elements into the REST variable
t = 1.2.3.4.5
a, b, *rest, c = t
print(a, b, c) 5 # 1, 2
print(rest) # [3, 4]
Copy the code
- If you don’t care about rest variables, use the wildcard “*” followed by the underscore “_”
t = 1.2.3.4.5
a, b, *_ = t
print(a, b) # 1 2
Copy the code
string
Definition of a string
Strings in Python are defined as collections of characters between quotes. Python supports the use of pairs of single or double quotes
- Common escape characters in Python
Escape character | describe |
---|---|
\ \ | Backslash notation |
‘ | Single quotes |
“ | Double quotation marks |
\n | A newline |
\t | Horizontal TAB (TAB) |
\r | enter |
The original string is simply preceded by the letter r
print(r'C:\Program Files\Intel\Wifi\Help')
# C:\Program Files\Intel\Wifi\Help
Copy the code
Triple quotation marks allow a string to span multiple lines. Strings can contain newlines, tabs, and other special characters
Slicing and concatenation of strings
- Similar to tuples being unmodifiable
- Starting at 0 (same as Java)
- A slice is usually written in the form start:end and includes elements corresponding to the “start index” but not the elements corresponding to the “end index”.
- The index value can be positive or negative. The positive index starts at 0 and runs from left to right. The negative index starts at -1 and goes from right to left. When a negative index is used, the count starts 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] + "Insert string" + str1[6:)# I Love insert 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 the code
Common built-in methods for strings
- Capitalize () converts the first character of a string to uppercase
- Lower () converts all uppercase characters in the string to lowercase.
- Upper () converts lowercase letters in a string to uppercase letters.
- Swapcase () converts uppercase to lowercase and lowercase to uppercase in a string.
- Count (STR, beg= 0,end=len(string)) count(STR, beg= 0,end=len(string)) count(STR, beg= 0,end=len(string)
- Endswith (suffix, beg=0, end=len(string)) checks if the string endswith the specified substring suffix, returning True if so, False otherwise. If beg and end specify values, check within the specified range.
- Startswith (substr, beg=0,end=len(string)) checks if the string begins with the specified substring substr, True if so, False otherwise. If beg and end specify values, check within the specified range
- Find (STR, beg=0, end=len(string)) checks whether STR is contained in the string, if the ranges beg and end are specified, and returns the starting index if so, otherwise -1.
- Rfind (STR, beg=0,end=len(string)) is similar to find(), but starts from the right
- Isnumeric () returns True if the string contains only numeric characters, False otherwise
- Ljust (width[, fillchar]) returns a left-aligned original string and fills it with fillchar (the default space) to a new string of length width.
- Rjust (width[, fillchar]) returns a right-aligned original string and fills it with fillchar (the default space) to a new string of length width
- Lstrip ([chars]) cuts off Spaces or specified characters to the left of the string.
- Rstrip ([chars]) removes Spaces or specified characters at the end of the string.
- Strip ([chars]) performs lstrip() and rstrip() on strings
- Partition (sub) finds the substring sub, divides the string into a triplet (pre_sub,sub,fol_sub), and returns (‘ original string ‘,”,”) if the string does not contain sub.
- Rpartition (sub) is similar to the partition() method, but looks from the right
- Replace (old, new [, Max]) replaces old in a string with new, up to Max times if Max is specified
- Split (STR =””, num) split(STR =””, num) no argument By default, the string is split with a space separator. If num is set, only num substrings are split, and a list of spliced substrings is returned
- Splitlines ([keepends]) returns a list of lines as elements separated by lines(‘\r’, ‘\r\n’, \n’), without newlines if keepends is False, and with newlines if True
- Aketrans (intab, outtab) creates a transformation table of character maps, the first argument being a string indicating the character to be converted, and the second argument being a string indicating the target of the transformation.
- Translate (table, deletechars=””) translates the characters of the string according to the table given by the parameter table, and places the characters to be filtered into the deletechars parameter
String formatting
- Format Format function
str8 = "{0} Love {1}".format('I'.'Lsgogroup') # position parameter
print(str8) # I Love Lsgogroup
str8 = "{a} Love {b}".format(a='I', b='Lsgogroup') # Keyword argument
print(str8) # I Love Lsgogroup
str8 = "{0} Love {b}".format('I', b='Lsgogroup') The positional argument should precede the keyword argument
print(str8) # I Love Lsgogroup
str8 = '{0:.2f}{1}'.format(27.658.'GB') Keep two decimal places
print(str8) # 27.66 GB
Copy the code
- Python string formatting symbol
Operator, | describe |
---|---|
%c | Format characters and their ASCII codes |
%s | Format the string and process the object with the STR () method |
%r | Format the string and process the object with the rper() method |
%d | Formatted integer |
%o | Format an unsigned octal number |
%x | Format an unsigned hexadecimal number |
%X | Formatted unsigned hexadecimal number (uppercase) |
%f | Format a floating-point number that specifies the precision after the decimal point |
%e | Format floating point numbers with scientific notation |
%E | Same as %e, uses scientific notation to format floating-point numbers |
%g | Use %f or %e depending on the size of the value |
%G | Same as %g, using %f or %E depending on the size of the value |
- Formatting operator auxiliary instructions
symbol | function |
---|---|
m.n | M is the minimum total width to display and n is the number of decimal places (if available) |
– | Used for left alignment |
+ | Display a plus sign (+) before a positive number |
# | Display zero before octal numbers (‘0’) and either ‘0x’ or ‘0x’ before hexadecimal numbers (depending on whether ‘x’ or ‘x’ is used) |
0 | The number displayed is preceded by a ‘0’ instead of the default space |
The dictionary
Mutable versus immutable types
- Unlike sequences, which are indexed by consecutive integers, dictionaries are indexed by “keys”, which can be of any immutable type, usually strings or values.
- Dictionaries are Python’s only mapping type, and strings, tuples, and lists are sequences
How do you quickly determine if a datatype X is mutable? The two methods
- Troublesome method: use id(X) function, perform some operation on X, compare the id before and after the operation, if different, then X is immutable, if the same, then X is variable
- Quick fix: Hash (X), as long as no error is reported, X can be hashed, i.e. immutable, and vice versa, can be changed
Dictionary definition
Dictionaries are unordered sets of key:value pairs. The keys must be distinct (within the same dictionary).
- There is no relationship between the order in which the dict is stored and the order in which the key is placed.
- Dict lookups and inserts are extremely fast and don’t increase with keys, but they take up a lot of memory
The dictionary defines the syntax as {element 1, element 2… , n} elements,
- Each of these elements is a key-value pair — key:value
- The key points are “curly braces {}”, “comma,” and “colon:”.
- Braces – Bind all elements together
- Commas — Separate each key-value pair
- Colon – Separates key and value
Create and access dictionaries
brand = ['李宁'.'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 = {'李宁': '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 the code
Create a dictionary with a string or numeric key
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 the code
If the selected key does not exist in the dictionary, a KeyError is reported
- Dict () creates an empty dictionary
A key can be used to put data directly into the dictionary. However, a key can only correspond to one value. If a value is added to a key multiple times, subsequent values will flush out previous values
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 the 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 the code
- dict(**kwargs)
dic = dict(name='Tom', age=10)
print(dic) # {'name': 'Tom', 'age': 10}
print(type(dic)) # <class 'dict'>
Copy the code
Built-in methods for dictionaries
- Dict.fromkeys (seq[, value]) is used to create a new dictionary with elements in the sequence seq as the dictionary keys, and value as the initial values of all keys in the dictionary
- Dict.keys () returns an iterable that can be converted using list() to a list of all the keys in a dictionary
- Dict.values () returns an iterator that can be converted using list() to a list of all the values in the dictionary
- Dict.items () returns a traversable array of (key, value) tuples as a list
- Dict.get (key, default=None) returns the value of the specified key, or the default if the value is not in the dictionary
- Dict.setdefault (key, default=None) is similar to get() in that if the key does not exist in the dictionary, the key is added and the value is set to default
dic = {'Name': 'Lsgogroup'.'Age': 7}
print("Age key value: %s" % dic.setdefault('Age'.None)) The # Age key has the value: 7
print("The Sex key value is: %s" % dic.setdefault('Sex'.None)) The # Sex key has the value: None
print(dic)
# {'Age': 7, 'Name': 'Lsgogroup', 'Sex': None}
Copy the code
- The key in dict in operator is used to determine whether a key is in the dictionary. Returns true if the key is in the dict, false otherwise. The not in operator, on the other hand, returns false if the key is in the dict, and true otherwise
- Dict.pop (key[,default]) deletes the value corresponding to the given key in the dictionary, and returns the deleted value. The key value must be given. If the key does not exist, the default value is returned.
- Del dict[key] Deletes the value of a given dictionary key
- Dict.popitem () randomly returns and removes a pair of keys and values from the dictionary, raising a KeyError if this method is called when the dictionary is already empty
- Dict.clear () is used to delete all elements in the dictionary
- Dict.copy () returns a shallow copy of a dictionary
- Dict. update(dict2) Updates the key:value pair of the dictionary parameter dict2 to the dict
A collection of
In Python, sets, like dict, are a set of keys, but do not store values. Because the key cannot be repeated, there is no duplicate key in set.
Note that key is of immutable type and can be hashed
Characteristics unordered and unique
num = {}
print(type(num)) # <class 'dict'>
num = {1.2.3.4}
print(type(num)) # <class 'set'>
Copy the code
Collection creation
- Create the object before you add the element
- You can only use s = set() when creating empty collections, because s = {} creates an empty dictionary
- Simply enclose a bunch of elements in curly braces {element 1, element 2… , n} elements,
- Duplicate elements are automatically filtered in set
- Use the set(value) factory function to convert a list or tuple into a collection
Because a set stores an unordered collection, we cannot create an index or slice for the collection. There are no keys to retrieve the values of the elements in the collection, but we can tell if an element is in the collection
Access the values in the collection
- You can use the len() built-in function to get the size of the set
s = set(['Google'.'Baidu'.'Taobao'])
print(len(s)) # 3
Copy the code
- You can use for to read the data from the collection one by one
s = set(['Google'.'Baidu'.'Taobao'])
for item in s:
print(item)
# Baidu
# Google
# Taobao
Copy the code
- You can determine whether an element already exists in a collection by in or not in
s = set(['Google'.'Baidu'.'Taobao'])
print('Taobao' in s) # True
print('Facebook' not in s) # True
Copy the code
The built-in methods of the collection
- Set.add (elmnt) is used to add elements to the collection. If the added elements already exist in the collection, nothing is done
- Set.update (set) is used to modify the current collection. You can add new elements or sets to the current collection. If the added element already exists in the collection, the element will appear only once
- Set.remove (item) is used to remove the specified element from the collection. If the element does not exist, an error occurs
- Set.discard (value) removes the specified collection element. The remove() method gets an error when removing a nonexistent element, while the discard() method does not
- Set.pop () is used to randomly remove an element
Because a set is a collection of unordered and non-repeating elements, two or more sets can perform mathematical set operations
- Set. Intersection (set1, set2) returns the intersection of two sets.
- Set1 & set2 returns the intersection of two sets.
- Set.intersection_update (set1, set2) intersection removes non-overlapping elements from the original set
- Set.union (set1, set2) returns the union of two sets.
- Characters | set2 returned two collections and set
- Set.difference (set) Returns the difference set of the set.
- Set1 – set2 returns the difference of the set.
- Set.difference_update (set) Sets of differences that directly remove elements from the original set, with no return value
- Set.symmetric_difference (set) returns xor of the set.
- Set1 ^ set2 returns xor of the collection.
- Set.symmetric_difference_update (set) removes elements in the current collection that are the same in another specified collection and inserts elements in another specified collection that are different from the current collection
- Set. Issubset (set) Determines whether a set is included by another set, True if so, False otherwise.
- Set1 <= set2 determines whether the collection is contained by another collection, and returns True if it is, False otherwise
- Set.issuperset (set) is used to determine whether the set contains – other sets, and returns True if it does, and -false otherwise.
- Set1 >= set2 determines whether the collection contains other collections and returns True if so, False otherwise
- Set.isdisjoint (set) Is used to determine whether two sets do not intersect, returning True if so and False otherwise
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 the code
Immutable set
Python provides an implementation version of a collection of elements that cannot be changed, that is, added or removed, of a type called Frozenset. Note that FrozenSet can still do collection operations, just not with an UPDATE.
- Frozenset ([iterable]) returns a frozenset after which no more elements can be added or removed.
a = frozenset(range(10)) # Generate 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 the code
The sequence
In Python, sequence types include strings, lists, tuples, collections, and dictionaries. These sequences support some general operations, but in particular, collections and dictionaries do not support indexing, slicing, adding, and multiplying
Built-in functions for sequences
- List (sub) converts an iterable to a list
a = list(a)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 the code
- Tuple (sub) converts an iterable to a tuple
a = tuple(a)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 the code
- STR (obj) converts an obj object to a string
a = 123
a = str(a)
print(a) # 123
Copy the code
- Len (s) returns the length or number of elements of the object (characters, lists, tuples, and so on)
- S – object
a = list(a)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 the code
- Max (sub) returns the maximum value in a sequence or set of parameters
print(max(1.2.3.4.5)) # 5
print(max([-8.99.3.7.83])) # 99
print(max('IloveLsgoGroup')) # v
Copy the code
- Min (sub) returns the minimum value in a sequence or set of parameters
print(min(1.2.3.4.5)) # 1
print(min([-8.99.3.7.83])) 8 # -
print(min('IloveLsgoGroup')) # G
Copy the code
- Sum (iterable[, start=0]) returns the sum of the sequence iterable and the optional argument start
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 the code
- Sorted (iterable, key=None, reverse=False) sorts all iterable objects
- Iterable — iterable.
- Key — A comparison element that takes only one argument. The argument to the function is taken from the iterable, and an element in the iterable is specified for sorting.
- Reverse — Collation, reverse = True descending, reverse = False ascending (default).
- Returns a 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 the code
- The reversed(seq) function returns an iterator that is reversed
- Seq – The sequence to convert, be it a 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 the code
- Enumerate (sequence, [start=0]) Combines an traversable data object (such as a list, tuple, or string) into an index sequence that lists data and data subscripts at the same time. It is usually used in a for loop
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 the code
- zip(iter1 [,iter2 […]])
- It is used to take the iterable object as a parameter, pack the corresponding elements of the object into tuples, and then return the object composed of these tuples. The advantage of this method is to save a lot of memory.
- You can use the list() transformation to output the list.
- If the iterators do not have the same number of elements, it returns the same list length as the shortest object. Using the * operator, you can unpack the tuple into a list.
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 the code