Lists in Python (list), tuples (Tuple), dictionaries (Dict), and collections (set) __python

Source: Internet
Author: User
Tags delete key throw exception in python

One, list (lists)
Defines a list using a pair of middle (square) brackets "[]".

One of the data types built into Python is a list: Lists are an ordered collection of data that can be added and deleted randomly. For example, list all the names of all the students in the class, and list all the work numbers of the factory employees.

Do not know if there is no one like me, just contact list to say this order is not very understand, do not know what is orderly. When I look up the information myself, I know that this order is not to say that the elements of the list are automatically lined up, and that the following is the case:

>>> List1 = [' 1 ', ' 2 ', ' 3 ']
>>> list2 = [' 2 ', ' 3 ', ' 1 ']
>>> list1 = = List2
False
>>> List1 is List2
False
>>> list3 = [' 1 ', ' 2 ', ' 3 ']
>>> list1 = = List3
True
>>> List1 is list3< C9/>false
>>>

In other words, Python is divided into locations, and this is ordered.

Let's look at some basic operations of the list in Python.
1. You can use the Len () function to get the length of the list (the number of elements in the dictionary);
2. You can use indexes to refer to elements in a list, noting that the index in the list starts at 0 and that negative indexes are also supported in the list;
3.list is a variable ordered list, so you can add and remove elements to your own list: Add elements at the end with the append () method, insert the element at the specified position using the Insert () method;
4. Delete elements in the list: Delete the end of the element using the Pop () method, delete the specified location of the element using pop (i), where I is the index subscript;
5. If you want to replace an element in the list, you can assign the element directly to the corresponding element subscript;
6. In a list can have different data types, can have string type, integer, or bool, and the list element can also have another list, which is equivalent to a loop nested.

List method:

L.append (Var)          #追加元素
L.insert (index,var)
L.pop (Var)               #返回最后一个元素 and removed from list
l.remove (Var)            #删除第一次出现的该元素
L.count (Var)             #该元素在列表中出现的个数
L.index (Var)             #该元素的位置, no throw exception
L.extend (LIST6)         # Append List6, that is, merge list to L, note here that using the Extend function you can insert any number of values in one list at a time without having to insert l.sort () one value at a time with only append ()        #排序
L.reverse ()     #倒序
del l[1]        #删除指定下标的元素
del L[1:3]      #删除指定下标范围的元素

#复制list:
L1 = L      #L1为L的别名, with C is the pointer address the same, to the L1 operation is the L operation.
L1 = l[:]   #L1为L的克隆, that is, another copy.
List1 = [' You ', ' Me ', ' her ', ' he ', 1000, 100000.123]

print list1 print
len (list1)
print list1[1],list1[-1]< C3/>list1.append (' It ']
list1.insert (3, ')
print List1

list1.pop ()
list1.pop (1)
print List1

list1[2] = ' Hello '
print list1

list2 = [' Wang ', ' Wu ', ' Luo ', [' Lang ', ' Luo ', ' Zhang '], ' Kua ']
print List2
print list2[3][1]

list1.extend (list2)
print List1

Output:

[' You ', ' Me ', ' her ', ' he ', 1000, 100000.123]
6
me 100000.123 [' You ', ' Me ', ' her ', ' ' I ', ' he
', 1000, 100000.123, ' it ']
[' and ', ' her ', ' ', ' he ', 1000, 1 00000.123]
[' You ', ' her ', ' hello ', ' he ', 1000, 100000.123]
[' Wang ', ' Wu ', ' Luo ', [' Lang ', ' Luo ', ' Zhang '], ' Kua ']
luo
[' You ', ' her ', ' hello ', ' he ', 1000, 100000.123, ' Wang ', ' Wu ', ' Luo ', [' Lang ', ' Luo ', ' Zhang '], ' Kua ']

Two, tuples (Tuple)
Define a tuple using a pair of small (round) brackets "()".

Like a list, tuples are also a sequence table, although tuple and list are very similar, but list initialization makes it possible to change, but once the tuple is initialized, it cannot be changed. This is similar to the strings in Python, so we say that tuples and strings are immutable sequences.

Now tuple can not be changed, and it has no append (), insert () such a method. The other way to get the element is the same as the list, you can use tuple[0],tuple[-1 normally, but you can't assign a value to another element.
What is the meaning of immutable tuple. Because the tuple is immutable, the code is more secure. If possible, use tuple instead of list as much as possible with tuple.

Tuple's Trap :
1. When you define a tuple, the elements of the tuple must be determined when defined;
2. When defining a tuple of only one element, this is required:
Tuple1 = (123,)
A comma is added later because the parentheses () can represent both tuple and parentheses in the mathematical formula, which creates ambiguity.
Tuple2 = (123) # If you define this to be the element of 123, not a tuple.
Python also adds a comma when displaying a tuple of only 1 elements, lest you misunderstand the parentheses in the meaning of the mathematical calculation.

The element values in the tuple are not allowed to be modified, but we can combine the tuples:

>>> T1 = (' wuyanl ', ' luoting ', ' Aimeiyu ')
>>> t2 = (1,2,3,4,5,6,7,8,9,0)
>>> T1 

(' wuyanl ', ' luoting ', ' Aimeiyu ')
>>> T2
(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
>>> t3 = T1 +t2
>>> T3
(' wuyanl ', ' Luotin G ', ' Aimeiyu ', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
>>>

The element values in the tuple are not allowed to be deleted, but we can use the DEL statement to delete the entire tuple.

Built-in functions for tuples:
1. Comparison of two tuple elements: CMP (TUPLE1,TUPLE2) equivalent to return 0, unequal return 1;
2. Calculate the length of a tuple: Len (tuple
3. Returns the minimum value of the maximum value in a tuple: max (tuple), min (tuple);
4. Convert list to infinitesimal group: Tuple = Tuple (list).

Three, dictionary (Dict)
Define Dictionary using a pair of large (curly) brackets "{}".
A dictionary (Dictionary) is one of the built-in data types of Python that defines a one-to-one relationship between keys and values, but they are stored in a disorderly manner. The "value" in the dictionary is referenced by a key.

Unlike lists: dictionaries are unordered, and the dictionaries are accessed by keys to access members.
Dictionaries are mutable and can contain any other type

Statement:
M={K1:V1,K2:V2}
Visit M[K1] will get V1

Common Dictionary operations:
Dic.clear () Empty dictionary
Dic.keys () Gets the list of keys
Dic.values () Get a list of values
Dic.copy () Copy Dictionary
Dic.pop (k) Delete key k
Dic.get (k) to obtain the value of the key K
Dic.update () Update member, if member does not exist, equivalent to join
Dic.items () Gets a list of keys and values

Get () Syntax:
Dict.get (Key, Default=none)
Parameters
key– the key to find in the dictionary.
default– if the value of the specified key does not exist, the default value is returned.
return value
Returns the value of the specified key, if the value does not return the default value of none in the dictionary.

#字典操作  
m = {' A ': 1, ' B ': 2, ' C ': 3}  
print (m)  
#读取某一个_通过key  
print (m[' a '])  
#读取某一个, through the Get Method  
print ( M.get (' B '))  
#复制字典  
m2 = m.copy ()  
print (m2)  
#获取所有键的列表  
print (M.keys ())  
#获取所有值的列表  
Print (M.values ())  
#获取所有键值对元组组成的列表  
print (M.items ())  
#更新成员, when the corresponding key value does not exist, the equivalent of adding  
m.update ({': 4})  
print (m)  
#删除某个成员  
m.pop (' a ')  
print (m)  
#遍历 from
key in M.keys ():
    if (key== ' x '):
        del M[key]

Four, set (set)
The Python collection (set), like other languages, is a unordered set of distinct elements that include relational testing and elimination of duplicate elements.

#定义一个集合 Set1 = {1, 2, 3, 4, 5} # or use the Set function List1 = [6, 7, 7, 8, 8, 9] Set2 = set (List1) Set2.add (10) # Add new element print Set2 # set ([8, 9, 6, 7]) removes duplicate content and is unordered Set3 = Frozenset (list1) #固定集合 Set3.add (10) # Fixed collection cannot add element #方法 (all collection Methods): S.issubset (t) # Returns true if S is a subset of T, otherwise returns false S.issuperset (t) #如果s是t的超集, returns True, otherwise returns false S.union (T) #返回一个新集合, which is the set of S and T S.intersection ( T) #返回一个新集合, the set is the intersection of S and T #返回一个新集合 s.difference (t), which is a member of S but not a member of T, that is, the element s.symmetric_defference (T) that returns s that is different from T #返回所有s和t独有的 (
Non-shared element collection s.copy () #返回一个s的浅拷贝, efficiency is better than factory #方法 (for variable collections only): The following method parameters must be hash s.update (t) #用t中的元素 modify S, that is, s now contains members of S or T S.intersection_update (t) #s中的成员是共同属于s和t的元素 s.difference_update (t) #s中的成员是属于s但不包含在t中的元素 S.symmetric_difference_ Update (t) #s中的成员更新为那些包含在s或t中, but not the element S.add (obj) that is common to s and T #在集合s中添加对象obj s.remove (obj) #从集合s中删除对象obj If obj is not an element in set S (obj not In s), will raise the Keyerror error S.discard (obj) #如果obj是集合s中的元素, remove the object obj s.pop () #删除集合s中得任意一个对象 from the set S, and return it S.clear () #删除集合s中的所有元素 # #
Set has a set of parallel sets, intersection, difference Operation # # and set: Intersection () method returns a new collection containing all elements that occur simultaneously in two collections. # # Intersection: UNThe ion () method returns a new collection containing the elements that appear in two collections.
# # Difference Set: the difference () method returns a new collection that contains all the elements that appear in collection A but are not in set B.
The # # Symmetric_difference () method returns a new collection containing all elements that appear only in one of the collections. # Delete Element Set2.discard (6) # When an element does not exist, an exception is not thrown Set2.remove (6) # The difference from discard is that if there are no elements to delete, remove throws an exception Set2.pop () # Because the set is unordered, So pops randomly removes an element from the 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.