Python Basics-List, Ganso, dictionary, string

Source: Internet
Author: User

Lists and groupings

Sequence Overview:

A data structure is a collection of elements that are organized in some way together . The elements can be numbers, characters, or even other data structures.

In Python, the most basic data structure is the sequence (sequence).

Each element in the sequence is assigned an ordinal----the position of the element, also known as Index, subscript. The first index is 0, the second index is 1, and so on.

Python contains 6 built-in sequences that focus on two of the most commonly used types: list, Ganso . Other built-in sequence types include: string,Unicode string,buffer object, and xrange Object . The next step is to explain the operations that are common to all sequences.

Creation of lists and Ganso:

The main difference between a list and a ganso is that the list can be modified, and the meta-ancestor cannot be modified. This means that if you need to add elements as required, the list might be better, and for some reason the sequence cannot be modified, and it is more appropriate to use Ganso.

Create a list, as long as the comma-separated data items are enclosed in square brackets;

Create a meta-ancestor, as long as the comma-separated data items are enclosed in parentheses, if there is only one element in the tuple, then you must add a comma after this element, otherwise it is not a tuple.

General sequence Operations:

All sequence types can perform a specific operation. These operations include indexes (indexing), shards (slicing), plus (adding), multiplication (multiplying), and checking that an element is a member (membership) of a sequence, in addition to the built-in function that calculates the length of the sequence, finds the largest element, and the smallest element.

1. Index

All elements in a sequence are numbered: increments from 0. These elements can be accessed individually by number. These numbers are the indexes. Index 0 points to the first element.

When using a negative index, Python starts counting from the right, which is the last element. The position number of the last element is-1.

If a function call returns a sequence, it is possible to index the returned result directly. For example, you are only interested in the 4th number of users entering the year:

2. Sharding

An index accesses a single element, and shards can access a range of elements. Shards are implemented by two indexes separated by a colon.

The first index is the number of the first element to extract, and the second index is the number of the first element of the remainder after the Shard; in short, "Gu Tou ignores the tail".

Step: When making shards, the default step is 1, we can also display the setting step, if the step is set to a number greater than 1, then some elements will be skipped.

For example, a shard of step 2 includes elements from start to finish every 1

The step can not be 0, error, but can be negative, when the Shard from right to left to extract elements.

1, when the step is positive, the starting index is less than the end index, otherwise it will be taken to the empty

2, when the step is negative, the starting index is greater than the end index, otherwise it will be taken to the empty

3. When the step is negative and the start index is empty, the start index defaults to the last index +1

4, when the step is negative, the end index is empty, the end index defaults to 0

3. sequence addition

You can make a sequence of connection operations by using the plus operator.

Only two sequences of the same type can be connected, or an error will be made:

4. Multiplication

By multiplying the number x by the sequence, a new sequence is generated. In the new sequence, the original sequence is repeated x times.

None , empty list, and initialization

An empty list can be represented simply by two brackets ([]).

None is a python built-in value that stands for "nothing Here"

If you want to initialize a list of length 10:

5. Member qualifications

In order to check whether a value is in a sequence , you can use the in operator.

This operator checks if a condition is true and then returns the appropriate value: True for the condition ; condition is false, return False.

Such an operator is a Boolean operator , and the value returned is a boolean value.

6. Length, minimum value, maximum value

Len function: Returns the number of elements contained in a sequence

Min function: Returns the smallest element in a sequence

Max function: Returns the largest element in a sequence

Basic list Operations

1. Changing the list: assigning values to an element

Use index markers to assign values to a specific, well-positioned element.

Note: You cannot assign a value to an element that does not exist in a location

If a list length is 5, you cannot assign a value to an element with a position of 11.

2. Deleting an element

The DEL statement implements the deletion.

List method

1.append

The Append method is intended to append a new object to the end of the list.

Add an object with a value of 100 at the end of the X list:

2.count

The Count method counts the number of occurrences of an element in the list.

Count the number of occurrences of 1 in the X list:

3.index

The index method is used to find the indexed position of the first occurrence of a value from a list.

Look for the first position where the element with the value 1 in the X list appears:

When the found element does not exist:

4.insert

Inserts an element at the specified location.

Insert ' Hong Kong ' after ' Beijing ':

5.pop

Removes a specified element from the list (the default is the last one).

Remove the last element and remove the element with the corner labeled 0:

The pop has a return value:

6.remove

Removes the first occurrence of a value in the list.

Delete the first element in the X list with a value of 1:

No return value, as opposed to pop.

7.reverse

Stores the elements in the list in reverse.

No return value, as opposed to pop.

8.sort

Sorts the list in the original location. (both letters and kanji can be sorted.) )

Ascending: List name. sort (); Descending: List name. sort (reverse=True)

This is a bad practice when you need a well-ordered list copy and you want to keep the original list intact, because the sort method does not return a value.

Finally, the ordered X and the null y are obtained.

The correct way is to assign X to Y first:

Dictionary:

A dictionary consists of key-value pairs that consist of multiple keys and their corresponding values. The key is separated from its value with a colon ":" and the item is separated by a comma "," and the entire dictionary is enclosed by a pair of curly braces "{}".

The keys in the dictionary are unique and the values are not unique. The dictionary printout is unordered.

1. Enquiry

D[K]: Returns the value associated to the key K.

An error occurs when accessing a key that does not exist in the dictionary:

Get method: When accessing a key that does not exist in the dictionary, it does not give an error, but gets none. You can also define the "default" value yourself, replacing none.

2. Increase

D[K]=V: Associates The value V to the key K.

If the key k does not exist, add a key k and the corresponding value;

If the key k exists, overwrite the original value.

SetDefault method: Similar to the Get method, the value associated with a given key can be obtained, and the corresponding key value can be set if the dictionary does not contain a given key.

When the key is present, it returns its corresponding value without changing the dictionary;

Updates the dictionary when the key does not exist.

3. Delete

Del D[k]: Delete the key with K.

Pop method: Gets the value corresponding to the given key, and then removes the key-value pair from the dictionary.

4. Empty the Dictionary

Clear method: Clears all the entries in the dictionary, with no return value (or none returned).

5. Get Dictionary Content

Print (D.values ()): Prints all values

Print (D.keys ()): Prints all keys

Print (D.items ()): Prints all keys and corresponding values

Print nested dictionaries: print (first dictionary name [' Second dictionary '] [' Third dictionary '] ... [' list '])

6. Cycle

Note: The order of the dictionary elements is usually unordered.

1) directly loop a dictionary, the loop is the key of the dictionary;

If you only need a value, you can use D.values (),

2) simultaneously get the value of the key and key:

7. Check if D contains an entry with a key of K

Print (key in D)/print (key no in D)

String

1.strip

Returns a string that strips both sides (excluding the interior) of spaces and newline (\ n):

Input (). Strip (): Remove spaces from input values

Remove the specified value:

2.count

Count the number of occurrences of a string:

3.index

Find the index position of the first occurrence of a value.

4.find

Finds a substring in a string that returns the leftmost index at the location of the substring. If not found, returns-1.

5.replace

Replace the string by replacing "day" with "Day":

6.isdigit

Determines whether a string is a purely numeric

7.startswith

Determine whether to start with a string

8.endswith

Decide whether to end with a string

9.upper: Returns the uppercase version of the string

Lower: Returns the lowercase master of a string

10.isalpha

Determine if a string is all words

11.isalnum

Determines whether letters and numbers are included, and returns True if there are letters or numbers

Python Basics-list, Ganso, dictionary, string

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.