Python 3 study notes: sequence

sequence

index

Is a sequence for placing a plurality of contiguous memory space worth, and arranged in a specific order, each value (called elements) are assigned an integer (from left to right starting from 0; -1 from right to left starting from ), referred to as an index (index), or, as shown below:

Python 3 study notes: sequence

You can get the actual value of each element of the index

string = "waterfalls three thousand feet, the suspect Galaxy nine days."
Print (String [5])
to copy
the operating results of the above statement is "thousands."

slice

A slice is another method to access elements in the sequence, the method may access the elements within a certain range.

1
Sequence [startIndex: endIndex: step]
Copy
If startIndex is not specified, the default starting from 0; if endIndex is not specified, the default until finally the end of the slice; if the step is not specified, the default is 1, and the front of the colon It can be omitted.

Sequences are added

In Python plurality of sequences of the same type of support for the addition (or more accurately spliced), the operation sequence will simply spliced ​​together, without any other additional operation.

seq_1 = "waterfalls three thousand feet,"
seq_2 = "suspected Galaxy nine days."
Print (seq_1 + seq_2)
copy
, of course, after the mosaic is actually get a new sequence, its index will be reordered.

Multiplying the sequence

Multiplication mathematical sense is to get a result after adding a number of repeat several times, the same is true sequence of multiplication, will also get a new sequence after repeating several times a splice sequence.

1
2
sequence = "Hello, Python !"
print(sequence * 3)
复制
in

in keyword is used to check whether an element is detected in the sequence,

1
Element in Sequence
copy
in front in not adding keywords, then check if the sequence is not detected in an element,

1
Element in Sequence not
copy
If the above two operations are met, the return True, otherwise False.

Only ()

len () method for calculating the length of the sequence, i.e., the number of elements in the sequence,

. 1
len (Sequence)
Copy
max ()

max () method of calculating the maximum value of elements in the sequence

1
max (Sequence)
copy
We know that numbers can compare the size, then the sequence (such as strings, lists, etc.) is how to compare the size of it? In the comparison of the time sequence, the element will first convert the ASCII code table to digital, and then compared, so that you can obtain a maximum or minimum, such as:

. 1
2
SEQ = "the Hello, the Python!"
Print (max (SEQ))
replication
result is a lowercase y.

max () function all the elements of the first seq (each letter, punctuation) is converted into ASCII code value, and then remove the maximum code value print elements. Our common characters, such as numbers, letters, etc., in the ASCII code value of the size of the table number followed <uppercase <lowercase letters. Of course, ASCII code table not only contain numbers, letters, of which there are many punctuation marks, special symbols (the specific code table to find your own).

Of course, if we want to verify the result of max () function to get the correct, you can use the ord () function to get the ASCII value of each element in seq,

seq = "Hello, Python!"
lst = []

for n in range(len(seq)):
lst.append(ord(seq[n]))

print (lst)
copying
the result is [72, 101, 108, 108, 111, 44, 32, 80, 121, 116, 104, 111, 110, 33], the maximum value of 121 can be seen, and we then chr () function to see what the ASCII value of 121 corresponds to a character that,

. 1
Print (CHR (121))
replicate
the results obtained are lowercase y.

(I)

min () function is used to calculate the minimum of elements in the sequence, the same principle as max () function.

String

Continuous string is a sequence of characters, it may be a set of all characters can be represented by a computer.

String immutable in Python programming, since there is no character set (char) type, it is usually quoted string (including single and double quotation marks, three quotes), three quotes no essential difference, but single quotes, double quotes the content must be in the same row, and three marks may be on a continuous multi-line.

Common Operations

String concatenation

Use the "+" operator plurality of strings may be stitched together to generate a string.

Repeat string

Using the "*" operator can repeat a string, like numerals multiplication.

Calculating the length of the string

Use len () function to obtain the number of characters in the string,

. 1
len (String)
Copy
wherein, string to be counted represents the length of the string.

EN () function when calculating the string length, does not distinguish between symbols, numbers, and characters, all characters are by one character is calculated.

However, depending on the coding mode, the number of bytes occupied by different characters (mainly for Chinese characters, such as the use GBK / GB2312 coding, two bytes representing characters; If using UTF-8 / unicode encoded characters representing the 3 or 4 bytes. in Python programming, numbers, letters and symbols, and spaces account for a byte underscore). Therefore, if necessary to obtain the actual number of bytes occupied by the string, through the need to encode () method to specify the encoding format, for example:

print (len ( "put up with a degree of free human; keep going, so that better!" encode ( "utf-8")).)

print (len ( "put up with a degree of free human; keep going, so that better!" encode ( "gbk") ).)
replication
can be seen that according to the operation result, the same sentence, in UTF-8 encoding each kanji characters, 3 bytes, and if the encoding GBK character for each character occupies 2 bytes.

Interception string

String is taken slice manner,

. 1
String [startIndex: endIndex: STEP]
Copy
split & merge string

Split string
string string list into the specified delimiter, this list does not include the separator element,

. 1
String.split (Symbol, maxsplit is)
replication
wherein, symbol representing the separator; maxsplit is represented by the number of divisions, if not specified number of times is not restricted.

. 1
Print ( "put up with a degree of freedom human, keep moving forward, so that the better" .split ( ","))
Copy
combined string
merging and segmentation is just the opposite string, a plurality of strings is fixed delimiter connected,

. 1
String = symbol.join (Sequence)
Copy
e.g.,

. 1
2
. 3
List = [ "Bob", "red", "Xiaogang"]
String = "@." The Join (List)
Print (String)
Copy
search character string

It offers a variety of statements specified search string methods in Python.

count ()
This method is often specified string in another string for retrieving, returns 0 if it does not exist, otherwise the number of occurrences,

. 1
string.count (the substring, startIndex, endIndex)
copy
string represents a string is being sought; represents the substring find substring; startIndex represents the start position of an index, it defaults to zero; endIndex index represents the end position, the default is the last an index of characters.

. 1
Print ([ "Bob", "red", "Xiaogang"] .count ( "red"))
Replication
find ()
which contains a specified method for detecting whether the substring, if there is no return - 1, otherwise the index of the substring to return for the first time,

. 1
to string.find has (the substring, startIndex, endIndex)
replication
e.g.,

1
Print ( "Xiao Gang and Xiao Ming go with little red house guest" .find ( "red"))
copied
in
this key is used to determine whether a substring exists in the target string is True is returned, otherwise return False,

1
substring in String
Copy
example,

if "red" in [ "Bob", "red", "Xiaogang"]:
Print ( "TRUE")
: the else
Print ( "FALSE")
copied
index ()
similar to the index () and find () method, also for detecting whether a target character string contains the specified substring, but using the index () when the detection method, if there is no exception is thrown,

. 1
string.index (the substring, startIndex, endIndex)
replication
e.g.,

. 1
Print ([ "Bob", "red", "Xiaogang"] .index ( "red"))
Copy
startsWith ()
This method starts with whether the detection target string specified substring, if it returns True, otherwise it returns False,

. 1
String.startsWith (the substring, startIndex, endIndex)
replication
e.g.,

1
Print ( "red Xiao Ming and Xiao Gang invited to a guest house" .startswith ( "red"))
copy
endswith ()
method to detect whether the target string ends with the specified substring, if it returns True, otherwise returns False,

. 1
string.endswith (the substring, startIndex, endIndex)
copied
letter case change

lower ()
This method is used to convert a string of uppercase to lowercase.

. 1
string.lower ()
Copy
upper ()
This method is used to convert a string in lowercase to uppercase.

1
string.upper ()
to copy
the removal of special characters & spaces

strip ()
method for removing a string left and right sides of the space (including spaces, tabs, carriage returns, line feeds, etc.) and special characters,

. 1
string.strip (Symbol)
Copy
the lstrip ()
This method is used in spaces left string and special characters removed

. 1
string.lstrip (Symbol)
replication
The rstrip ()
This method is used in the right spaces and special characters removed string

. 1
string.rstrip (Symbol)
copy
format string

Refers to a format string to develop a template, the template set aside some space in, and then fill in the corresponding content according to needs. These vacancies needed (i.e., a placeholder) designated by a symbol mark, and these symbols will not be displayed.

% Using operator
. 1
"% [-] [+] [0] [m] [. N-] [Symbol]"% strTuple
replication
in this way is provided a method of early Python, Python 2.6 since the beginning of the string format provided () method of the string format (currently more recommend this approach formatted string), so there is not too much to learn.

format () method
The basic syntax,

. 1
stringTemplate.format (args)
Copy
stringTemplate style for displaying the specified character string, i.e., the stencil; args for the actual contents of the specified alternative placeholder template, a plurality of entries separated by commas.

When you create a template, you need to use braces and colons designated placeholder syntax is as follows,

1
{index:[fill][align][sign][#][width][.precsion][type]}
复制
Python 3 study notes: sequence

Wherein the type of the following type:

Python 3 study notes: sequence

List

A series arrangement of elements in a particular order, these types of elements can be any data type in Python. Variable sequence list is built Python, in the form, all the elements is placed in brackets ([]), two adjacent elements with a comma (,) separated. Elements in the list may be independent of each other between different data types, elements and elements without disturbing each other.

Create a list

Just give the list specifies an identifier, then the elements into which you can:

1
List = [ "the Hello", "Python", 2019, 7, 31]
copy
, of course, in the actual programming process, we can also create an empty list, and then again when needed, which put in elements

1
List = []
Copy
Delete List

When we do not need a list, just use the del statement to delete:

1
del List
Copy
Access list elements

Possible because a list is also a sequence, so you can also use the index, way to get a slice of the elements in the list.

Operation list elements

Adding elements

Can append () method of adding an element to the end of the list,

. 1
list.append (Element)
copying
the method only additional element to the end of the list, and if you want to insert an element into the middle of the list, the following method may be used,

. 1
list.insert (index, Element)
copy
insert () method inserts an element to the specified index, the element of the original position and the subsequent elements are automatically to a retracted, i.e. its original index plus one.

The above two methods are want to add a single element in the list, if you want to add another to the list of a list, you can use the following methods,

. 1
list.extend (sequence)
replication
elements in the sequence which will be appended to the original order of the list at the end.

Sample code:

list = ["hello", "python"]

append () method

list.append(2019)
print(list)

insert () method

list.insert(2, "world")
print(list)

extend () method

sequ = [ "world", "rise and fall"]
list.extend (sequ)
Print (List)
Copy
modified element

By the index to locate the elements you want to modify, and then give it directly to the assignment,

1
List [index] = newValue
copy
remove elements

By deleting the index
and modify elements similar to index positioning elements to be deleted, and then use the del key to delete,

. 1
del List [index]
Copy
deleted as the value of the element
using a list remove () method implementation,

1
list.remove (elementValue)
copy
of the list of Statistics and Computing

Gets the number of times an element that appears
to use a list of count () method gets the number of an element of the list,

1
list.count (Element)
Copy
Gets the index of the first occurrence of an element
() method gets the index of the first occurrence of the specified element in this list by the index of the list,

. 1
list.index (Element)
Copy
seeking purely digital elements of the list and
if the elements of a list of all digital, may use the sum of the list () method to find all of the elements and,

. 1
SUM (List, Addend)
replication
wherein, Addend is optional, default value of 0, if specified, and coupled with the elements of the list on the basis of Addend, such as:

list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Print (SUM (List))
Print (SUM (List,. 3))
to copy
the list of elements to sort

sort () method
which is used to sort the elements of the list as specified, the sorted index of the element will change,

. 1
the list.sort (key = None, Reverse = False)
Copy
key extracted from each element is used to specify the key for comparison; Reverse default is False, it indicates ascending order, if the descending order is True.

sort () method does not return a value, so only after the list is sorted, the output of the list,

list = ["hello", "Python", "world", "Welcome", "list"]

list.sort ()
Print (List)
replication
are digital for all elements of the list is sorted very simple, if the string element is sorted, the first sort of uppercase letters, lowercase letters and then to sort. To sort case-insensitive, to specify the value of the key parameters, such as key = str.lower.

Also, note that if a list of elements in both figures, there are strings, you can not use the sort () method sorts.

sorted () function
in Python, provides a built-sorted () function is used to sort the list, the method returns a list of the sorted list is kept and the original,

. 1
new_list The the sorted = (old_list, key = None, reverse = False)
Copy
wherein interaction parameters and key and reverse sort () method parameters as, for example:

old_list = ["hello", "Python", "world", "Welcome", "list"]

new_list = sorted(old_list, key=str.lower, reverse=True)
print(new_list)
复制
元组

Similar lists and tuples, but also a series of elements arranged in a specific order (which may be of any data type in Python) composition, but tuples are immutable sequence, i.e. can not be added to the tuple, remove elements. Formally, all elements of the tuple is placed in a pair of parentheses, two adjacent elements separated by commas, no relationship between the elements. Since the immutable characteristics of tuples, the tuple is generally used to store the program content can not be modified.

Creating a tuple

Just to give a tuple identifier is specified, then the elements can be filled therein,

1
tuple = ( "the Hello", "Python", 2019, 7, 31)
copy
, we can also create an empty tuple,

. 1
tuple = ()
replication
in Python tuple is not necessarily enclosed in parentheses will be used, as long as a group of elements to be separated by commas, can Python them as tuples,

. 1
tuple = "Hello", "Python", 2019,. 7, 31 is
replicated
when we use the print () function to print the tuple, these elements will be enclosed in parentheses.

If you create a tuple only one element, you need to add a comma after the element, otherwise the tuple will be treated as a string, or other data types.

Delete tuple

Because tuples would no longer have to create change, you can only delete all tuples, but can not remove elements of them,

1
del tuple
copy
access tuple elements

Element is one sequence, it can also use the index, which slices the access element.

The difference between tuples and lists

Variable sequence belongs to a list, which elements can be modified or deleted; and the tuples can not only replace the whole
tuple access and processing speed than the list
of tuples as dictionary key, the list not
dictionaries

In Python, the dictionary is a variable sequence, but no index dictionary, but in the key - the value of the stored data. Dictionary has about features;

Read by the key instead of index
dictionary is a collection of arbitrary objects without
dictionary is variable, and may be arbitrarily nested
dictionary keys must be unique
dictionary key must be immutable
create dictionaries

When the dictionary definition, each element comprising two portions keys and values, separated by colons therebetween to form an element, and the elements are separated by commas elements,

. 1
Dictionary = {Key_1: VALUE_1 of, Key_2: VALUE_2, ..., key_n: value_n}
copy
tuple key for each element must be unique, immutable, can be numbers, strings or tuples. The value of the element can be any data type in Python, and may not be unique.

In addition to directly create a dictionary, can also dict () and zip () function list, a dictionary combined into tuples,

. 1
Dictionary = dict (ZIP (tuple, list))
replication
If tuple and the length of the list are different, the same short length create a dictionary as a reference.

Delete dictionary

Delete dictionary can also use del keywords,

1
del the Dictionary
copy
if you do not delete the dictionary, but only want to delete all its elements, you can use the clear () method,

1
dictionary.clear ()
to copy
access dictionary element

Because the dictionary Unlike lists, tuples have the same index, it can not be indexed, sliced ​​way to access its elements. Dictionary can only access their corresponding values ​​from the key.

Operating dictionary elements

Adding elements

Dictionary variable sequence is the same as the list, so you can add elements to which only need to specify the keys and values ​​to the elements,

. 1
Dictionary [key] = value
replicate
unless the bond can exist in the newly added key already exists in the dictionary.

Modify elements

Modify the elements of the dictionary is actually a disguised form of added elements, just key value already exists in the dictionary, it will replace it with the corresponding value to a new value.

Removing elements

Delete dictionary elements can also use del keywords,

1
del the Dictionary [key]
copy
will delete key element of the dictionary, the corresponding value will be deleted, this element does not exist in the dictionary.

set

The set of mathematical and Python is similar set, is used to hold the elements will not be repeated, and a variable set of immutable set two kinds. Separated by commas between form, the elements of the collection, all the elements are in braces. A collection of the best application is to remove duplicate elements, because each element in the collection is unique.

Create Collection

Directly to all the elements enclosed in parentheses, and can be given an identifier,

. 1
SET = {ELEMENT - 1, element_2, ...,} element_n
copy
if a create time, a plurality of input accidentally repeating elements, Python automatically keep only one.

We can also use the set () function lists, tuples converted into the set,

1
the SET = the SET (List / tuple)
copy
if we want to create an empty set, they can only use the set () method, instead of using empty curly braces (because empty braces indicate an empty dictionary).

Delete Collection

You can use the same set of keywords del delete,

. 1
del SET
copy
operations binding

Adding elements

Can add () method was added to the collection element,

1
set.add (Element)
copy
remove elements

You can pop () or remove () method to remove elements of the collection, or use clear () method of emptying the collection element,

. 1
set.pop ()
Copy
pop () method deletes the first element in the collection order.

1
Set.remove (Element)
copy
remove () method to specify the elements to be deleted, if the element does not exist, an exception is thrown.

1
set.clear ()
copy
clear () method removes all elements in the collection, so that it becomes an empty set.

Set Operations

Intersection

In Python, & intersection using sets using symbols operation.

Union

In Python, using sets and set using | symbol calculation.

Difference set

In Python, difference using sets using - calculation symbols.

Symmetric difference

In Python, symmetric difference using sets used for computing the caret.

E.g,

1
2
3
4
5
6
7
set_1 = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}
set_2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

print(set_1 & set_2)
print(set_1 | set_2)
print(set_1 - set_2)
print(set_1 ^ set_2)

Guess you like

Origin blog.51cto.com/14499640/2429604