Python container--list, tuple, dict, set

Source: Internet
Author: User
Tags iterable set set shallow copy

# # Python has four kinds of sequences for storing data--list, tuple, dict, set


# # List
-an ordered sequence of data of any type can be stored
-a list can consist of 0 or more elements, separated by commas, and the entire list wrapped in square brackets:
-Create
-Create a list using [] or list ()
-New_list = ["Stanley", "Loves", "Lily"]


-Access and modification
-use list name [index] to access and modify list elements, index initial value is 0, maximum value does not exceed list length-1
-Print (new_list[1]) #-"Loves"
-new_list[1] = "Adore"
-Print (new_list) #--[' Stanley ', ' adores ', ' Lily ']
-If the index can be negative, start counting from the end of the list with 1 as the initial value


-Generate a new list using [Start, end, step] shards (new and old lists in different memory addresses)
-[:] Extracts the entire string from the beginning to the end
-[start:] Extract from start to end
    -[: end] extracted from the beginning to End-1
-[start:end] extracted from start to end-1
-[start:end:step] extracted from start to end-1, every step of the character extraction
-Start,end,step can be negative, start and end are negative to indicate from right to left, count from 1, step is negative to reverse


-common list-related functions
-len (a_list): Return list length
-a_list.append (new Element): Add new element to end of list
-A_list.extend (anoth Er_list): Add Another_list to the end of a_list, you can use + = to achieve the same effect, a_list + = Another_list
-A_list.insert (index, new Element): Inserts a new element into the list at the specified position, If the value of index is greater than the list length, the new element is inserted at the end of the list
-del A_list[index]: Deletes the element at the specified position, the value of index must be less than the list length
-del is not a function, but a Python statement, which is the inverse of an assignment statement (=)       , it unlocks the binding between the variable and the value
-a_list.remove (Element): Delete the element of the specified value
a_list = [' A ', ' B ', ' C ']
A_list.remove (' B ')
Print (a_list) #--[' A ', ' C ']
-a_list.pop (index): pops up the element at the specified position, index defaults to-1
-A_list.index (Element): If the list has a specified element, returns the index of the element
-uses in to determine if a value exists in a list, returns true if it does not exist, returns false
-A_list.count (Element): Returns the number of occurrences of an element in the element
-A_lis T.sort (): list sort, default to ascending, by adding parameter reverse=true can be changed to descending order
-a_list.copy (): Returns a new list with different memory addresses but the same list value, shallow copy, only one layer of content can be copied, The memory address for the nested list does not change


-List Modification Issues
Example
A = [1, 2, 3] #--Create a new list
b = a # Let B and a point to the same memory address
B[1] = "A" #--Modify the second element in the list by B
Print (a) # output [1, ' A ', 3], because it points to the same memory, so the modification of B will also affect a

-You can generate a new list of different memory addresses through the copy () function, list () conversion function, and [:] shard, so that modifications to the new list do not affect the contents of the old list


# # Tuple tuples
-Create tuples with () or tuple ()
-tuples can be considered as immutable lists
-relatively, tuples occupy less space than lists
-The tuple attribute and list are basically the same, but cannot use related functions that change element content, such as append (), insert (), etc.
-Create considerations
-there is only one element in the Jo Yuan group, after which a comma is required to indicate that this is a tuple
-can also be created without parentheses, but need to have a comma after the element to indicate that this is a tuple
A = 1,
Print (Type (a)) #-<class ' tuple ' >

# # Dict Dictionary
-A combination of data, no order, and data in the form of a key-value pair
-Create: D = {} or D = Dict ()
D = {
Key1:value1,
Key2:value2,
...
Key_n:value_n
}


-Features
-Dictionaries are sequence types, but unordered sequences, so no indexes and slices
-All data in the dictionary is a key-value pair
-Key must be a hash value, such as int str, float, tuple, etc., but list, set, Dict, etc.
-Value can be anything
-delete: Del Dic[key] #, delete entire key-value pairs


-Correlation function
-D.keys (): Returns the dictionary key
-D.values (): Returns the value of the dictionary
-D.items (): Returns the dictionary data in a list format
D = {
"Name": "Stanley",
"Age": 22
}
Print (D.items ()) #-Dict_items ([' Name ', ' Stanley '), (' age ', 22)])
-D.clear (): Empty
-D.get (key[, default)): According to the key, return the corresponding value, the advantage is that you can set the default value, if the parameter key does not exist in the dictionary, will not error, but return the default value passed in
-Dict.fromkeys (): uses the specified sequence as the key, using a value as the value of all keys of the dictionary
A_list = [1, 2, 3, 4]
D = Dict.fromkeys (A_list, "Love")
Print (d) #-{1: ' Love ', 2: ' Love ', 3: ' Love ', 4: ' Love '}

# Set Set
-set is a concept in high school mathematics
-a bunch of determined unordered unique data
-You can also use curly braces to define, but you must have values in curly braces


Characteristics
-The data in the collection is unordered, that is, indexes and slices cannot be used
-Collection of internal data is unique and can be used to exclude duplicate data
-Data in the collection, such as str, int, float, tuple, etc., can be hashed
-the collection itself is not hashed


function
-S.add (): Adding elements to the collection
-S.clear (): Empty collection (original collection operation)
-S.copy (): Shallow copy
-S.remove (value): Removes the specified value, if no value in the collection will be given an error
-S.discard (value): Removes the specified value and does not error if no value is in the collection
-S.pop (): Randomly pops up a value in the collection without parameters
-S1.intersection (S2): Intersection
-S1.difference (S2): Difference Set
-S1.union (S2): the Set
-S1.issubset (S2): Checks whether the collection S1 is a subset of the collection S2
-S1.issuperset (S2): Checks whether the collection S1 is a superset of the collection S2


-Mathematical operation of the set
S1 = {1, 2, 3}
S2 = {2, 3, 4, 5}
S3 = S2-s1
Print (S3) #, {4, 5}


-Frozen Set frozen set
-Frozen set is a collection where no modifications can be made
-Create: s = Frozenset ()
-This is a special collection with all the features except for modifying the outer collection

# # list, tuple, dict, set all can be generated using derivation
-List derivation format: [Expression for item ' in Iterable if condition],if filter condition can be omitted, the same format applies to tuple and set, but the brackets need to be modified to () and {} respectively
A_list = [n for n in range (1, ten) if n% 2 = = 0]
Print (a_list) $, [2, 4, 6, 8]
-Dictionary derivation format: {key_expression:value_expression for expression in iterable}
A_list = [n for n in range (1, 5)]
B_list = ["A", "B", "C", "D"]
C_dict = {K:b_list[k-1] for k in A_list}
Print (c_dict) #, {1: ' A ', 2: ' B ', 3: ' C ', 4: ' d '}


Book: [American]bill Lubanovic "Python language and its application"

Python container--list, tuple, dict, set

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.