Python basic Syntax _ basic data type _ detailed sequence type

Source: Internet
Author: User
Tags iterable

Directory

    • Directory
    • Sequence
    • Standard operators for sequences
      • Slice operator
      • An example
    • function function of sequence
      • Enumerate the elements of a Sequence object
      • Len gets the length of the sequence object
      • Min Remove the minimum value from the sequence
      • Max takes out the maximum value in the sequence
      • Reversed returns an iterator that is accessed in reverse order
      • Ordering of sorted sequences
      • Sum computes the elements in the sequence and
      • Zip Blend two Sequence objects
      • All detects whether each element in the sequence is true
      • Any detects if any element in the sequence is true

Sequence

A sequence is a generic term for a class of basic data types (strings/lists/tuples) that contain some common attributes. For example, a data type object can contain several elements, which are arranged in an orderly manner and can be used to access one or several of the elements through the subscript index.

The sequence type contains:

    • String strings
    • Tuple tuples
    • List lists
Standard operators for sequences

Applies to all sequence types

sequence operator
Seqname[number]
seqname[num1:num2] Get index from NUM1 to num2 The element collection between
seqname \* copies_int
Join operator (|) seq1 + seq2
member relationship operator (In/not in) obj in/not in seq

Note : Using the Join operator (+) to combine the contents of two sequences is not the quickest and most efficient method.

    • When merging string type objects, it is recommended join() to call the function, which saves memory more.
    • When merging list type objects, it is recommended to use the built-in functions of the list type, extend() but note that this function changes the original list object, and the function of the Mutable type Object extend() does not return a value.

Of course, the best way to do this is to look at the specific situation.

Slice operator []/[:]/[::]

Sequences allow an element to be obtained by means of subscripts, or by specifying the subscript range to obtain a set of elements of a sequence, the way in which the sequence of accesses is called a slice .

mode one : [] Get an element of a sequence

    • Index offset is positive: range is 0 <= index <= len (seqname)-1
    • Index offset is negative: Range -len (seqname) <= index <=-1
      The difference between positive and negative indexes is that the positive index starts with the beginning of the sequence and the negative index begins with the end of the sequence.

Note: Len () is a sequence-type built-in function that can get the length of a sequence, that is, the number of elements.
Note :
1. When using the [] mode, the value of index cannot go out of range, otherwise it will error Indexerror
2. The index value is starting from 0

mode two : [:] Gets a set of elements of a sequence

seqName[starting_index:ending_index-1#获取由starting_index开始至ending_index结束之间的元素

Note :
1. When using the [:] method, the value of index can be out of range without error.
2. The index value is starting from 0

In [23]: alist = [1,2,3,4,5]In [24]: alist[:100]         #ending_index超出了范围,但仍然没有报错;start_index的缺省值 == 0,ending_index的缺省值为len(seqName)Out[24]: [12345]

Way Three : [::] Step Index
The last slice operation of a sequence is an extended step slice operation, that is, the third index value.
Step : Based on the obtained sequence of cut films, follow a certain step in order to get the elements.
EXAMPLE1: Get an element from every other person

In [48‘abcdefghijk‘In [49]: aStr[::2]Out[49‘acegik‘

EXAMPLE2: Reverses the contents of a sequence

In [50]: aStr[::-1]Out[50‘kjihgfedcba‘
An example

There is a string that we want to display in a loop, and each time we display it, we chop down the last character.

in [ -]: AStr =' Abcdefghijk 'in [ Wu]: Range (-1,-len (ASTR),-1) out[ Wu]: [-1, -2, -3, -4, -5, -6, -7, -8, -9, -Ten]in [ About]: forIinch[None]+range (-1,-len (ASTR),-1):    ...:PrintASTR[:I] ...: Abcdefghijkabcdefghijabcdefghiabcdefghabcdefgabcdefabcdeabcdabcaba

Of course, if we change the String in the example above into a List or a Tuple, this trick will be very useful.
Note:
1. Range () is a number list generator and also supports stepping operations
2. For the first print to be able to print the String completely, you need to use aStr[:None]
3. Reverse Delete element aStr[:-index]
4. The For loop in Python can traverse all of the iterated type objects

function function of sequence

Note : The following functions len() / reversed() //can sum() only accept sequence type parameters, and other function functions can receive all the iterated objects In addition to the sequence type parameters. When we are learning a function, we use Help () to look at the helper documentation for the function, which clearly indicates the types of arguments that the function can receive.

The following 4 types of objects can be iterated :
1. Sequence type List, String, Tuple.
2. Non-sequence type dict, file.
3. A custom class iterator for any include __iter__() or __getitem__() method.
4. Iterable (iterator), the function parameter contains iterable, which indicates that an iterator type argument can be passed.

Iteration: Iteration is the activity of repeating the feedback process, each repetition of the process is called an iteration, and the results of each iteration are the initial values for the next iteration. The concept of iteration in Python is generalized from sequences, iterators, and other objects that support iterative operations.

Enumerate () Enumerates the elements of a Sequence object

Enumerate (Sequence[,start = 0]) receives an iterative object as a parameter, returning an enumerate object (an iterator consisting of a tuple of index numbers and elements merged into one element). [,start = 0]parameter to specify the starting position of the index.

In [22‘jmilkfan‘In [23]: enumerate(aStr)Out[230x35d1550>     #返回一个enumerate对象,是一个迭代器In [25forin enumerate(aStr):    ...:     print"%s : %s" % (i,j)    ...:     0 : j1 : m2 : i3 : l4 : k5 : f6 : a7 : n
Len () Gets the length of the sequence object

accept only sequence type parameters
The length of the sequence object, that is, the number of sequence object elements

In [39‘Jmilk‘In [40]: len(name)Out[405
Min () Remove the minimum value from the sequence
In [28]: aStrOut[28‘jmilkfan‘In [29]: min(aStr)Out[29‘a‘

If the element is of type string, it is converted to ASCII code calculation and then compared.

Max () takes out the maximum value in the sequence

Like min () function

In [30]: max(aStr)Out[30‘n‘
Reversed () returns an iterator that is accessed in reverse order

Accept only sequence type object parameters
Reversed (sequence), reverse iterator over values of the sequence

In [31]: aStrOut[31‘jmilkfan‘In [32]: reversed(aStr)Out[320x36d4ed0>In [34forin reversed(aStr):    ...:     print i,    ...:        n a f k l i m j
Ordering of sorted () sequences

receives an iterative object that returns an ordered list.
Sorted (iterable, Cmp=none, Key=none, Reverse=false) –> new sorted list

    • Iterable: Receives an iterative object
    • CMP (x, y): Specifies a custom, capable of comparing two functions that receive parameters x, y, default to None.
    • Key (x): Specifies a function that receives a parameter, which is used to extract a key value as the comparison value in each element, and the default is None to compare each element.
    • Reverse:false is the default value for the positive order arrangement, and True is in reverse order.

Note 1: There are no __getitem__() objects, such as the int type, that cannot invoke key and CMP functions.
NOTE 2: There are many built-in functions in Python that can accept specifying a custom function such as map (), filter (), reduce (), including sorted, and so on, when using lambda The anonymous function will be very convenient.

sorting efficiency : key/reverse > CMP. Because the CMP function makes several 22 comparisons, Key/reverse will only be called once for each input record.

key function : Sort the comparison value with the second keyword

In [205]: li = [(‘a‘,3),(‘b‘,2),(‘c‘,1)]In [208lambda keyword:keyword[1#选择li[][1] ==> (3,2,1)作为比较的关键词Out[208]: [(‘c‘1), (‘b‘2), (‘a‘3)]

cmp function : Sort the second keyword as the comparison value

In [213lambda x,y:cmp(x[1],y[1]))   #会进入多次的两两(1,2)/(1,3)/(2,3)比较Out[213]: [(‘c‘1), (‘b‘2), (‘a‘3)]

Reverse: reverse order

In [216]: sorted(li,lambda z,x:cmp(z[1],x[1]),reverse=True)Out[216]: [(‘a‘3), (‘b‘2), (‘c‘1)]
SUM () computes the elements in the sequence and

sum () accepts only sequence type objects, but does not support sequences of elements of type string or char.
Sum (sequence[, start]), value
[, start]: You can specify an additive starting index.

inch[ -]: num = [1,2,3,4]inch[ -]: str =' MyName isJmilk 'inch[ A]: sum (num) out[ A]:Teninch[ +]: sum (str)---------------------------------------------------------------------------TypeError Traceback (most recent) <ipython-input- +-3A5f0824550a>inch<module> ()----> 1 sum (str)typeerror:unsupported operandtype(s) for+:' int‘ and ' str‘
Zip Blend two Sequence objects

Combines two elements of the same index in two sequence objects with the Narimoto group and takes these tuples as an element of the new list returned.

inch[ Wu]: alist out[ Wu]: [' my ',' name ',' is ',' Jmilk ']inch[ -]: Name out[ -]:' Jmilk 'inch[ About]: Zip (name,alist) out[ About]: [(' J ',' my '), (' m ',' name '), (' I ',' is '), (' l ',' Jmilk ')]
All () detects whether each element in the sequence is true

All true is true, anyway, is False.

In [63]: num = [1,2,3,‘‘]In [64]: all(num)Out[64FalseIn [65]: num = [1,2,3,True]In [66]: all(num)Out[66True

Note : Therefore, the null sequence object is False

Any () detects if any element in the sequence is true

True if True.

In [67]: num = [1,2,3,‘‘]In [68]: any(num)Out[68True

Python basic Syntax _ basic data type _ detailed sequence type

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.