Python, I learned from scratch t^t D5

Source: Internet
Author: User

Recently to go back to school to do the completion of the set, ready to do a related algorithm, I heard that Python operations better, specifically to learn.

Let's start with the basics .......... ...........

Slice

Taking a partial element of a list is a very common operation.

Python provides a slicing (Slice) operator that can greatly simplify this operation.

With the first 3 elements, you can complete the slice with one line of code:

L[0:3]

L[0:3] Indicates that the fetch starts at index 0 until index 3, but does not include index 3. That is, index 0,1,2, which is exactly 3 elements.

If the first index is 0, you can also omit:

L[:3]

You can also start with index 1 and take out 2 elements:

L[1:3]

Use only one: to indicate from beginning to end:

l[:]

So l[:] Actually copied out a new list.

The slice operation can also specify a third parameter:

L[::2]

The third parameter indicates that each n takes one, and the top L[::2] takes one out of every two elements, that is, one at a intervals.

Tuple ibid.

L[-1] is the last element to be used for reverse sectioning.

The reverse slice contains the starting index and does not contain the end index.

Use the reverse section to remove the 1-100 sequence:

* last 10 digits;

* A multiple of the last 10 5.

L = Range (1, 101)
Print l[-10:]
Print l[4::5][-10:]

Character slices

>>> ' ABCDEFG ' [: 3] ' ABC '

A collection is a data structure that contains a set of elements that we have covered: 1. Ordered collections: List,tuple,str and Unicode;2. Unordered collection: Set3. Unordered collections and have key-value pairs: dict

The enumerate () function puts:

[' Adam ', ' Lisa ', ' Bart ', ' Paul ']

Into something like this:

[(0, ' Adam '), (1, ' Lisa '), (2, ' Bart '), (3, ' Paul ')]
Using the enumerate () function, we can bind both index and element name in the For loop.
>>> L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']>>> for index, name in enumerate (L): ...     Print index, '-', name ... 0-adam1-lisa2-bart3-paul


The zip () function can turn two lists into a list:

>>> zip ([ten, +,], [' A ', ' B ', ' C ']) [(Ten, ' A '), (+, ' B '), (+, ' C ')]

The Dict object has a values () method, which converts the dict to a list containing all value

Dict In addition to the values () method, there is a itervalues () method that replaces the values () method with the Itervalues () method, which is exactly the same as the iteration effect

What is the difference between the two methods?

1. The values () method actually converts a dict to a list containing value.

2. However, the Itervalues () method does not convert, and it takes value from dict in sequence during the iteration, so the Itervalues () method saves the memory needed to generate the list, compared to the values () method.

3. Print itervalues () find it returns a <dictionary-valueiterator> object, which shows that in Python, the For loop can be used to iterate beyond List,tuple,str,unicode. Dict, and so on, any iterator object can be used for a for loop, and the inner iteration of how we usually don't care.

If an object says that it can iterate, then we iterate it directly with a for loop, which is an abstract data operation that does not require any data inside the iteration object.

In a For loop, how to iterate both key and value.

The value returned by the items () method of the Dict object:

>>> d = {' Adam ': $, ' Lisa ': $, ' Bart ':}>>> print d.items (' Lisa ', ' $ '), (' Adam ', $), (' Bart ', 5 9)]

As you can see, the items () method converts the Dict object to a list that contains a tuple, and we iterate over the list to get both key and value:

>>> for key, value in D.items ():     ... Print key, ': ', Value ... lisa:85adam:95bart:59

Like the values () has a itervalues (), items () also have a corresponding iteritems (), Iteritems () does not convert dict to list, but in the iterative process is given a tuple, so, Iteritems () No additional memory is consumed.

D.ieteritems ()

List-Generated
>>> L = []>>> for x in range (1, one): ...    L.append (x * x) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

But the loop is too cumbersome, and the list generation can use a line of statements instead of loops to generate the list above:

>>> [x * x for x in range (1, 11)][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]



The string can be formatted with%, replacing%s with the specified parameter. The join () method of a string can be used to stitch a list into a string.

If we want even squares, without changing the range (), you can filter by if:

>>> [x * x for x in range (1, one) if x% 2 = = 0][4, 16, 36, 64, 100]

With the IF condition, the current element of the loop is added to the list only if the if is judged to be True.

Isinstance (x, str) can determine if the variable x is a string

The upper () method of the string can return uppercase letters

In a list build, you can also use a multi-layer for loop to generate the list.

Python, I learned from scratch t^t D5

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.