Python first recognizes complex data types (list, dictionary, and tuple) and pythontuple

Source: Internet
Author: User

Python first recognizes complex data types (list, dictionary, and tuple) and pythontuple

In the previous article, we briefly understood the data types: number and string. In this article, we will introduce the heavyweight data types: list, dictionary, and metadata tuple.

I. List:

① What is the list?

For example, if I am a Tom, we can write me = 'Tom 'when defining variables '. Mom is a white mom mother = 'White mom ', Dad is a white Dad father = 'White Daddy '. ForOne-to-one, We can directly define variables. But if I want to express my family, define a variable named family, family = me + Mom + Dad. That

How should we assign values to it? The [List] concept is introduced here.

List format: List = [] # List marked by square brackets

List = [a, B, c, d] # elements in a, B, c, and d are separated by commas (,).

At this time, family = ['White modem', 'White modem', 'White modem']

List representsOne-to-multiple,The list element can be a number (1, 2, 3, 4), a string ('White ', 'White mom, 'White Daddy'), or even a list (nested). For example, if Tom is married to Tom and has a small family of his own, family1 = ['xiaobai', 'Little Black', 'Little White Mama ', 'Little white daddy'] at this time, in order to reflect the small

Bai and Xiao Hei are one of them. new_family = [['xiaobai', 'xiao hei'], 'Little white mom ', 'Little white daddy']. In this case, a small list element is nested in the family list. One contains a list, called a two-dimensional array; one contains a list, and the other sets a list. This is called a three-dimensional array,SetSeveral layers are the dimension list.

② How can we find Tom in family?

The list element has its own number. Its name is "subscript, index, badge, and number ". The subscript of the first element on the leftmost is 0, and the subscript of the last element on the rightmost is-1. Number from left to right, ascending sequentially, 0, 1, 2...; number from right to left, descending in turn,-1,-2,-3...

Find elements from the list:List [subscript]For example, in the family, the subscript of the small white is 0 or-3, so what the family [0] or family [-3] gets is the small white. How to output the entire family? Many people think that family [0: 2], but the actual operation will find that only "white" and "little white mom" can be output at this time, because the rule for selecting the subscript of list is "ignore head and tail ", therefore, only family [0: 3] or family [0:] can output all elements.

How can we find Tom in new_family? The answer is new_family [0] [0].When nesting multiple layers, remember not to worry. It is easy to retrieve them one layer at a time..

③ The following describes some common list operations:

Define a list: cities = ['guangzhou ', 'tianjin']

# Add

Cities. append ('beijing') # Add an element to the end of the list

Print (cities)> cities = ['guangzhou ', 'tianjin', 'beijing']

Cities. insert (0, 'shanghai') # Add an element at the specified position

Print (cities)> cities = ['shanghai', 'guangzhou ', 'tianjin', 'beijing']

# Delete

Cities. pop (0) # Delete the element at the specified position

Print (cities)> cities = ['guangzhou ', 'tianjin', 'beijing']

Cities. remove ('beijing') # delete a specified Element

Print (cities)> cities = ['guangzhou ', 'tianjin']

Del cities [-1] # Delete

Print (cities)> cities = ['guangzhou ']

Cities. clear () # clear list

print(cities)>> cities = []

# Change
Cities [1] = 'nanjing '# You need to specify the subscript for modification,If the specified subscript does not exist, an error is returned.

# Query
Print (cities [0]) # search at the specified location
Print (cities. index ('guangzhou ') # obtain the subscript of an element,If the element cannot be found, an error is returned.

Print (cities. count ('guangzhou ') # view how many times an element appears in the list

④ Common list methods:

# Reverse:

My_list = ['python', 'jmeter ', 'Charles', 'postman']
Print (my_list.reverse ())#Reverse my_list and NO content will be returned. Print the list again and you will find that the order has been modified.

print(my_list)>> ['postman', 'charles', 'jmeter', 'python']

# Sorting

Nums = [34,457,234, 2]

Nums. sort () # Ascending

print(nums)>>[2, 9, 12, 34, 34, 457, 2342]

Nums. sort (reverse = True) # descending order

print(nums)>>[2342, 457, 34, 34, 12, 9, 2]

# Merge

Print (cities + cities2) # merge list

# Copy
Print (cities * 3) # copy several times

 

Ii. Tuple:

The difference between tuples and lists is thatThe elements of the tuples cannot be modified..

Tuple format: Tuple = () # The tuples are identified by parentheses ''()''.

Tuple = (1,) # If there is only one element in the tuples, add a comma (,) after the element.

Tuple = (a, B,) # elements are separated by commas. The elements in the tuples can be numbers, strings, or nested types.

Note: although the tuples cannot be modified, they can be modified if the element contains a variable list or dictionary. For example:

nums = (9, 2, 34, ['test'])nums[3][0] ='a'print(nums)>>(9, 2, 34, ['a'])

① Common methods for tuples:

Print ('words2', type (words2) # view type
Print (t. index (2) # locate the subscript of the element
Print (t. count (2) # Find the number of elements in the tuples

 

3. Dictionary:

① What is a dictionary?

A dictionary, like a list, is a set of variable objects. Suppose we want to input a person's information, such as name: white, sex: female, Hoby: male, etc. We need to input both results and text descriptions. List can store results, but it cannot contain explanatory text. Therefore, we introduce a new data type-dictionary.

Dict: Dict = {key: value} # The dictionary is identified by curly braces ({}). The elements in the dictionary are in the key-value format, similar to json.

Dict = {'name': 'White ', 'sex': 'female', 'hobby': 'male'} # Use commas to separate the elements, the element can be a number, string, or nested type.

② Difference:

The list is ordered and the dictionary is unordered;

The elements in the dictionary are accessed by keys, while the List is accessed by subscript;

The key in the dictionary must be a unique identifier, just like the subscript of the list;

The dictionary value is faster than the list value;

③ Common dictionary operations:

Define a dictionary infos = {}

# Add

Infos ['name'] = 'xiaobai' # Add a key-value.
Infos. setdefault ('age', '25') # Add a key-value.
Infos. setdefault ('name', 'black') # If the key exists, the value in the original key is not modified.
Infos ['name'] = 'blacklist '# If the key exists, the value corresponding to the original key is modified. If the key does not exist, a new key-value is created.

# Delete

Infos. pop ('name') # specify the key to delete the key and the corresponding value.
Infos. popitem () # randomly delete a key and the corresponding value
Del infos ['phone'] # specify the key to delete the key. If the key exists, the key and value are deleted. If the key does not exist, an error is returned.
Infos. clear () # clear the dictionary

# Change

Infos ['name'] = 'yellow '# If the key exists, the value corresponding to the original key is modified. If the key does not exist, a new key-value is created.

# Query

Print (infos. get ('phone') # If this key is not obtained, None is returned.
Print (infos. get ('phone', 110) # If this key cannot be obtained, the default value is 110.
Print (infos ['phone']) # If the key does not exist, an error is returned.

④ Common dictionary methods:

Print (infos. values () # obtain all the values in the dictionary.

Print (infos. keys () # obtain all keys in the dictionary

Print (infos. items () # obtain all key-values in the dictionary

Tip:

Number and string are immutable and change is equal to a new one; tuple is unchangeable; list and dictionary are mutable

Number and string are one-to-one relationships. list, dictionary, and tuple are one-to-many relationships.

The above is all about this article. You still need to explain and practice how to use data types. The following are benefits:

 

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.