The first knowledge of Python (4) __python sequence

Source: Internet
Author: User

Sequence

Sequence contains: strings, lists, and tuples

Sequence basic operator

index : seq[ind] Get the element labeled IND

Shard ([], [:], [::]):Seq[ind1:ind2] Gets the set of elements from Ind1 to Ind2

repeat operator (*):seq * expr sequence repeats expr times

Join operator (+):Sequence1 + sequence2, the result of which is a new sequence containing the contents of Sequence1 and Sequence2

Judge membership:obj in/not in seq determines whether the obj element is contained in a SEQ, returns TRUE or False

Length:len ()

Maximum minimum value:max () min ()

About indexes:

Sequence[index]

Sequence is the name of the sequence, and index is the offset of the element that you want to access. The offset can be positive, ranging from 0 to the maximum offset (one less than the sequence length), with the Len () function (which is the next section) to get the sequence length, the actual range is 0 <= Inde <= Len (sequece)-1. Alternatively, a negative index can also be used, ranging from 1 to the negative length of the sequence,-len (sequence),-len (sequence) <= index <=-1. The difference between positive and negative indexes is that the positive index starts with the beginning of the sequence, Negative indexes start with the end of the sequence.

about slices:

Sequence[starting_index:ending_index]

In this way we can get a "slice" element between the starting index and the end index (excluding the element corresponding to the end index). Both the start and end indexes are optional, and if none is provided or the index value is not used, the slice operation starts at the beginning of the sequence. or until the end of the sequence. The last slice operation of an extended slice operation sequence with a step index is an extended slice operation, and its third index value is used as a step parameter. S[::-1] # can be seen as a "flip" action

sequence type conversion factory function

List (ITER): Converting an Iterative object to a list

STR (obj): Converts the Obj object to a string (the string representation of the object)

Unicode (obj): Converts an object to a Unicode string (using the default encoding)

Basestring (): Abstract factory function that simply provides the parent class for STR and Unicode functions, so it cannot be instantiated or called by a tuple (ITER): Convert an iterative object to a tuple object

String

Attributes: Created with quotation marks (single quotes, double quotes, three quotation marks), immutable types

Format

Describe

%%

Output percent sign

%c

Characters and their ASCII code

%r

Prioritize string conversions with the repr () function

%s

Prioritize string conversions with the STR () function

%d

Signed integer (decimal)

%u

unsigned integer (decimal)

%o

unsigned integer (octal)

%x

unsigned integer (hexadecimal)

%x

unsigned integer (16 uppercase characters)

%e

Floating-point numbers (scientific notation)

%E

Floating-point numbers (scientific notation, E instead of e)

%f

Floating point number (with decimal point symbol)

%g

Floating-point numbers (%e or%f depending on the size of the value)

%G

Floating-point numbers (similar to%g)

%p

Pointer (memory address of the value printed in hexadecimal)

%n

Stores the number of output characters into the next variable in the parameter list

Auxiliary symbols

Description

*

Define width or decimal precision

-

Used for left justification

+

Show plus sign (+) in front of positive number

<sp>

Show spaces in front of positive numbers

#

Display 0 (0) in front of octal numbers, "0x" or "0X" before hexadecimal (depending on "x" or "X")

0

The displayed number is preceded by "0" instead of the default space

M.n

M is the minimum total width displayed, and n is the number of digits after the decimal point (if available)

Note: The secondary symbol is to be between the percent sign (%) and the formatting symbol.

Examples of auxiliary symbols:

NUM1 = 108print("% #X" %= 234.567890print("%.2f  " % Num2) output:0x6c234.57

Primitive string operator (R/R)

The original string in Python begins with R, and using the original string avoids the problem with the literal character string.

' C:\noway ' Print  = r'c:\noway'print  path, the result is: C:\noway

List

The l list is a sequence object that can contain any Python data information, such as strings, numbers, lists, tuples, and so on.

The data of the list is variable, we can add, modify and delete the data in the list through the object method.

L can convert a sequence type to a list by using the list (SEQ) function

The list is defined by square brackets [], and of course you can create it using the Factory method list ().

' ABC ', 4.56, ['inner'list'], 7-9j]>> > List ('foo') ['f' o ' ' o ']

List method:

1.list.append (x), appending a single object x at the end of the list, using multiple arguments causes an exception

2. List.count (x), returns the number of times the object x appears in the list

3. List.extend (l), add the contents of the L list to the list and return none

4. List.index (Obj,i=0,j=len (list)): Returns the K value of List[k]==obj, and the range of K is i<=k<j, otherwise throws a ValueError exception

5. List.insert (i,x), insert object X before the element indexed to I, such as List.insert (0,X) Insert the object before the first item, return none

6. List.pop (x), delete the table entry with index x in the list and return the value of the table entry, and if no index is specified, POP returns the last item in the list

7. List.remove (x), delete the first element of the matching object x in the list, produce an exception when matching the element, return none

8. List.reverse (), reverse the order of the list elements

9. List. Sort ([cmp[, key[, reverse]]), sorts the list, returns the None,bisect module can be used to add and delete sorted list items

Sequence type functions

Len (): For Strings, Len () returns the length of the string, which is the number of characters that the string contains. For lists or tuples, it returns the number of elements in the list or tuple as you would think, and each object in the container is treated as an item.

Max () and Min ()

Sorted () and reversed (): sort

Enumerate () and zip ():

SUM (): Sum

List () and tuple (): the list () function and the tuple () function accept an iterative object (such as another sequence) as an argument and create a new list or tuple from a shallow copy of the data to convert between the two types. For example, you need to turn an existing tuple into a list type (and then you can modify its elements), or vice versa.

Meta-group

1, equivalent to immutable list, can not be updated content and order

2, when working with a set of objects, this group is the tuple type by default

3, all the multi-object, comma-delimited, not explicitly defined by the symbol of these are the tuple type by default

To create a tuple:

>>>atuple = (' 1', ' B ', ' a ')>>> tuple ('bar') ('  b'a'R')> >>atuple = (' 1 ',)  # Create a tuple of individual elements, add a "," number

About tuple operations:

1. Unable to add elements to the tuple. Tuples do not have a append () or extend () method.

2. You cannot delete an element from a tuple. The tuple does not have a remove () or pop () method.

3. You can find an element in a tuple, because the operation does not change the tuple.

4. You can also use the In operator to check if an element exists in a tuple.

Update tuples

As with numbers and strings, tuples are immutable types, that is, you cannot update or alter the elements of a tuple, and we do this by constructing a new string in the fragment of an existing string, which is also required for tuples.

Atuple = (123,'ABC', 4.56, ['Inner','tuple'], 7-9j) Atuple= Atuple[0], atuple[1], atuple[-1]Print(atuple) output: (123,'ABC', (7-9j)) Tup1= (12, 34.56) tup2= ('ABC','XYZ') Tup3= Tup1 +tup2Print(TUP3) output: (12, 34.56,'ABC','XYZ')

So what good is a tuple?

• Tuples are faster than lists. If you define a series of constant values, and all you need to do is traverse it, use a tuple substitution list.

• "Write protection" of data that does not need to be changed will make the code more secure. Using a tuple substitution list is like having an implied assert statement that shows that the data is constant, and special ideas (and special features) must be rewritten. (?? )

• Some tuples can be used as dictionary keys (especially tuples that contain immutable data such as strings, numeric values, and other tuples). The list can never be used as a dictionary key because the list is not immutable.

• Tuples exist as return values for many of the built-in functions and methods.

Reference: Http://hi.baidu.com/wuxinzy/item/c2c3cd428c99aa01896d10a7

about lists and lists, the comparison between tuples and tuples:

1. Compare the elements of the two list.

2. If the element being compared is of the same type, the value is compared and the result is returned.

3. If two elements are not of the same type, check whether they are numbers.

A. If it is a number, perform the necessary number to force the type conversion, and then compare.

B. If one of the elements is a number, the other party's element is "large" (the number is the "smallest")

C. Otherwise, the comparison is made by the alphabetical order of the type name.

4. If one list first reaches the end, the other longer list is "large".

5. If we run out of two list elements and all the elements are equal, then the result is a draw, which means returning a 0.

The first knowledge of Python (4) __python sequence

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.