[Python Notes] usage of list, tuple, set, and dict in python: pythontuple

Source: Internet
Author: User

[Python Notes] usage of list, tuple, set, and dict in python: pythontuple

List

List is an ordered set (or a list) that allows you to easily add and delete elements.

>>> Classmates = ['Michael ', 'bob', 'tracy']

Each element can be accessed by serial number, range:-n ~ N-1. When the index exceeds the range, Python reports an IndexError.

Append (...) new element: classmates. append ('miranda ')

Insert (...,...) insert the element to the specified position: classmates. insert (2, 'john ')

Pop () deletes the end element: classmates. pop ()

Pop (...) deletes the element at the specified position: classmates. pop (1)

Remove (...) deletes the element where the specified value first appears: classmates. remove ('bob ')

Count (...) counts the number of times a specified value appears: classmates. count ('bob ')

 

To replace an element with another element, you can directly assign a value to the corresponding index location:

>>> Classmates [1] = 'sara'

The Data Types of list elements can be different, for example:

>>> L = ['apple', 123, True]

The list element can also be another list, for example:

>>> s = ['python', 'java', ['asp', 'php'], 'scheme']>>> len(s)4>>> s[2][1]'asp'

Tuple

Tuple is also an ordered list, which is very similar to list. However, once initialized, tuple cannot be modified. It is a bit like the const type variable of C ++.

 

>>> classmates = ('Michael', 'Bob', 'Tracy')>>> classmates = tuple(['Michael', 'Bob', 'Tracy'])>>> hello = ('hello')

Because it cannot be modified, there is no such method as append (), insert (), pop.

When you define a tuple, The tuple elements must be determined. Two special definitions:

 

>>> t = ()   # empty tuple>>> t = (1,)  # tuple with only one element, ',' is necessary

 

A seemingly modifiable tuple:

 

>>> t = ('a', 'b', ['A', 'B'])>>> t[2][0] = 'X'>>> t('a', 'b', ['X', 'B'])

 

On the surface, the tuple elements have indeed changed, but in fact they are not the tuple elements, but the list elements. The list to which tuple points at the beginning is not changed to another list. Therefore, tuple's so-called "unchanged" means that every element of tuple will always point to it. That is, if you point to 'A', you cannot change it to 'B' or to a list. You cannot change it to another object, but the list itself is variable!

 

In some special circumstances, if you want to modify the non-list element of tuple, for example, you want to change t to ('1', 'B', ['A ', 'B']), which can be converted to list first, modified, and then returned to tuple:

 

>>> tl = list(t)>>> tl[0] = '1'>>> t = tuple(tl)

 

 

Set

Set is a set composed of keywords only. Keys are case-insensitive. Key must be an immutable object (int, float, bool, str, tuple)

. Add (key): add the element key to the set. It can be added repeatedly but it will not work.

. Remove (key): deletes the elements of a specified key.

Two sets can be used for intersection and Union operations:

 

>>> s1={1,2,3}>>> s2={2,3,4}>>> s1 & s2{2, 3}>>> s1 | s2{1, 2, 3, 4}>>> s1 ^ s2{1, 4}>>> s1 - s2{1}

 

 

Dict

Python's built-in dictionary type, which is short for dictionary, is equivalent to stl: map in C ++. It uses key-value pairs for storage and provides extremely fast search speed. It can be viewed as a set of binary groups.

For example, we want to create a "name-Score" ing table:

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}>>> d['Michael']95

 

A key can only correspond to one value. Therefore, if a key is put into a value multiple times, the subsequent value overwrites the previous value. The key must be an immutable object. If it is a string, the time zone is case sensitive.

Determine whether 'Thomas 'exists:

>>> 'Thomas 'in d # method 1 False >>> d. has_key ('Thomas ') # method 2 False >>> d. get ('Thomas ',-1) # method 3-1

. Pop (key): deletes an element with the key keyword.

. Keys (): returns the list of keys.

. Values (): returns the list of values.

. Items (): returns the list of binary groups (key, value ).

-- The above three functions do not need to generate a new list after adding iter to the name. This method is recommended for the time series, which saves memory. For example,. iterkeys ().

. Clear (): clear the dictionary

. Has_key (key): determines whether the dictionary contains a key keyword.

. Update ([B]): update the current dictionary with dictionary B. If it exists, modify it. If it does not exist, add it.

 

 

Reprinted please indicate the source: http://www.cnblogs.com/webary/p/5187217.html

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.