In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the basic knowledge points of Python3 collection set introduction", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the basic knowledge points of Python3 collection set introduction"?
A set is an unordered sequence of non-repeating elements.
You can create a collection using curly braces {} or the set () function. Note: to create an empty collection, you must use set () instead of {}, because {} is used to create an empty dictionary.
Collection, cousin of the dictionary {} is not the privilege of the dictionary
Features of the collection:
1 is unique and 2 does not support that index 3 is the same as a dictionary and is unordered.
Create a format:
Parame = {value01,value02,...} or set (value)
Creation method
Num1 = {1 num3.copy () temp = set (temp) print (temp) print (num1,num2) num3 = [1 num3.copy () temp = set (temp) print (temp)
Example
> basket = {'apple',' orange', 'apple',' pear', 'orange',' banana'} > print (basket) # the deduplication function {'orange',' banana', 'pear' is demonstrated here 'apple'} >' orange' in basket # quickly determines whether the element is in the collection True > 'crabgrass' in basketFalse > # below shows the operation between the two collections. > > a = set (' abracadabra') > b = set ('alacazam') > a {' axiang, 'ringing,' baking, 'centering,' d'} > a-b # elements contained in collection a but not in collection b 'b'} > a | all the elements in the b # collection {' a','c','r','d','b','m','z','l'} > a & b # sets an and b contain elements {'a','c'} > a ^ b # that are not contained in both an and b. 'zealous,'l'}
Similar to list derivation, the same collection supports set derivation (Set comprehension):
> a = {x for x in 'abracadabra' if x not in' abc'} > a {'ringing,' d'}
The basic operation of the collection
1. Add elements
The syntax format is as follows:
S.add (x)
Add the element x to the collection s and do nothing if the element already exists.
> thisset = set (("Baidu", "jb51", "Taobao") > thisset.add ("Facebook") > print (thisset) {'Facebook',' Taobao', 'Baidu',' jb51'}
The output is random and unsorted.
There is another way to add elements, and the parameters can be lists, tuples, dictionaries, and so on. The syntax format is as follows:
S.update (x)
X can have multiple, separated by commas.
> thisset = set (("Baidu", "Jb51", "Taobao") > thisset.update ({1pr 3}) > > print (thisset) {1Taobao', 3, 'Baidu',' Taobao', 'Jb51'} > thisset.update ([1p4], [5pc6]) > > print (thisset) {1p3, 4,5, 6,' Baidu', 'Taobao',' Jb51'} >
2. Remove elements
The syntax format is as follows:
S.remove (x)
Remove the element x from the collection s, and an error occurs if the element does not exist.
Instance (Python 3.0 +)
> thisset = set (("Baidu", "Jb51", "Taobao")) > thisset.remove ("Taobao") > print (thisset) {'Baidu',' Jb51'} > thisset.remove ("Facebook") # there is no error Traceback (most recent call last): File ", line 1, in KeyError: 'Facebook' >
Another way is to remove the element from the collection, and if the element does not exist, no error occurs. The format is as follows:
S.discard (x)
Instance (Python 3.0 +)
> thisset = set (("Baidu", "Jb51", "Taobao") > thisset.discard ("Facebook") # No error does not exist > print (thisset) {'Taobao',' Baidu', 'Jb51'}
We can also set an element in the collection to be randomly deleted. The syntax format is as follows:
S.pop ()
Script pattern instance (Python 3.0 +)
Thisset = set (("Baidu", "Jb51", "Taobao", "Facebook") x = thisset.pop () print (x)
Output result:
$python3 test.py
Jb51
The test results vary from time to time.
The pop method of the set collection arranges the collection out of order, and then deletes the first element on the left of the unordered collection.
3. Calculate the number of set elements
The syntax format is as follows:
Len (s)
Calculate the number of s elements in the collection.
Instance (Python 3.0 +)
> thisset = set (("Baidu", "Jb51", "Taobao")) > len (thisset) 3
4. Clear the collection
The syntax format is as follows:
S.clear ()
Empty the collection s.
Instance (Python 3.0 +)
> thisset = set (("Baidu", "Jb51", "Taobao") > thisset.clear () > print (thisset) set ()
5. Determine whether the element exists in the collection
The syntax format is as follows:
X in s
Determine whether the element x is in the set s, there is a return True, there is no return False.
Instance (Python 3.0 +)
> thisset = set (("Baidu", "Jb51", "Taobao") > "Jb51" in thissetTrue > "Facebook" in thissetFalse >
Complete list of built-in methods in the collection
Add () add elements to the collection clear () remove all elements in the collection copy () copy a collection difference () returns the subtraction of multiple sets difference_update () removes the element in the collection, which also exists in the specified collection. Discard () deletes the element specified in the collection intersection () returns the intersection of the collection intersection_update () returns the intersection of the collection. Isdisjoint () determines whether the two collections contain the same element, and returns False if no True is returned. Issubset () determines whether the specified set is a subset of the method parameter set. Issuperset () determines whether the parameter set of the method is a subset of the specified set pop () randomly removes the element remove () removes the specified element symmetric_difference () returns a set of elements that are not duplicated in the two sets. Symmetric_difference_update () removes elements in the current collection that are the same in another specified collection and inserts different elements in another specified collection into the current collection. Union () returns the union of two sets update () to add elements to the collection
Let's continue to add some examples for you.
S.update ("string") and s.update ({"string"}) have different meanings:
S.update ({"string"}) adds strings to the collection and ignores duplicates. S.update ("string") splits a string into individual characters and then adds them to the collection one by one. Any repetition will be ignored.
> thisset = set (("Baidu", "Jb51", "Taobao")) > print (thisset) {'Baidu',' Jb51', 'Taobao'} > thisset.update ({"Facebook"}) > print (thisset) {' Baidu', 'Jb51',' Taobao', 'Facebook'} > > thisset.update ("Yahoo") > > print (thisset) {' hindsight, 'oasis,' Facebook', 'Baidu',' Yee, 'Jb51',' Taobao','a'} >
Considerations for parameters in set ()
1. Create a collection that contains one element
> my_set = set (('apple',)) > my_set {' apple'}
two。 Create a collection that contains multiple elements
> my_set = set (('apple','pear','banana')) > my_set {' apple',' banana', 'pear'}
3. If not, do not write it in the following form
> my_set = set ('apple') > my_set {' lumped, 'paired,' a'} > my_set1 = set (('apple')) > my_set1 {' lumped, 'estranged,' paired,'a'}
The collection's different impression of deleting an element with the set.pop () method is as follows:
1. For the elements in the list list and tuple types in python, the conversion set is, and the duplicate elements are removed as follows:
> list = [1, list, 2, 3, 4, 5, 5] > set (list) {1, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, > > tuple = (2, 3, 5, 5, 5) > set (tuple) {2, 3, 5, 5, 6}.
2. The collection has a sort (ascending order) for list and tuple, for example:
> set ([9, 2, 4, 5, 6, 7, 7, and 1]) {1, 2, 4, 5, 6, 6, 7, 9} > > set ([9, 2, 4, 5, 6, 8, 9])
3. The set.pop () of the set is considered differently.
Some people think that set.pop () is a random deletion of an element in the collection, and I would like to say no here! Elements are randomly deleted for collections that are dictionaries and character conversions. When the collection consists of lists and tuples, set.pop () removes the element from the left as follows:
List example:
Set1 = set ([9, 4, 5, 5, 6, 7, 1, 8]) print (set1) print (set1.pop ()) print (set1)
Output result:
{1, 2, 4, 5, 6, 7, 8, 9} 1 {2, 4, 5, 6, 7, 8, 9}
Tuple instance:
Set1 = set ((6, 3, 1, 7, 2, 9, 8, 0) print (set1) print (set1.pop ()) print (set1)
Output result:
{0, 1, 2, 3, 6, 7, 8, 9} 0 {1, 2, 3, 6, 7, 8, 9}
> thisset = set (("Baidu", "Jb51", "Taobao", "Facebook") > y=set ({'python'}) > print (y.union (thisset)) {' python', 'Taobao',' Baidu', 'Facebook',' Jb51'}
Output result:
{'python',' Baidu', 'Taobao',' Facebook', 'Jb51'}
There is only one element 'python',' in the collection of y at this time, but if there are no curly braces, the collection of y contains five elements, namely, 'paired, grammatical, grammatical, and grammatical, which contains five elements, namely, paired, grammatical, grammatical, and grammatical.
> thisset = set (("Baidu", "Jb51", "Taobao", "Facebook") > y=set ('python') > print (y.union (thisset)) {' Baidu', 'Facebook',' Jb51', 'nasty,' t'}
You can also use parentheses:
Thisset = set (("Baidu", "Jb51", "Taobao", "Facebook")) y=set (('python','love')) print (y.union (thisset))
Output result:
{'Facebook',' Jb51', 'Taobao',' python', 'love',' Baidu'}
But when there is only one string in the collection of y, the result is the same as without curly braces.
The sort method of the list enables in-place sorting (no need to create a new object, and strings are sorted by the first letter):
A = [1, 51, 31,-3, 10] a.sort () print (a) s = ['a 'print ()] print (s)
Output:
[- 3, 1, 10, 31, 51] ['3eyed,' averse, 'ab', 'z']
Sort by the length of characters in the collection:
A = [1, 51, 31,-3, 10] a.sort () print (a) b = ['aaaaaaaaaaju (3)] b.sort () print (b) c = [c.sort (key=len) print (c)
Output:
[- 3, 1, 10, 31, 51] ['1years,' 3aetrees, 'asides,' ab', 'zaaa'] [' asides, '1tons,' ab', '3aesies,' zaaa']
Here are the supplementary pictures and texts of other netizens.
The collection is also a built-in data structure in python, which is a sequence of unordered and non-repeating elements. There are two keywords, one is unordered, which is the same as the dictionary, and the other is that the element does not repeat, which is the same as the dictionary's key (key). In this way, the collection looks like a dictionary, but in fact they also look alike:
Collections, like dictionaries, are wrapped in {}, so the question is, if you write only one {}, is it a collection or a dictionary?
No element in {} creates a dictionary, so the problem is again, how to create an empty collection? We can create it using the set () function. Now that the collection has been created, let's take a look at some uses of the collection.
1. Add elements to the collection:
The add function of a collection can add an element to the collection, and update can update one or more elements, whose arguments can be lists, collections, and so on.
two。 Delete the elements in the collection.
There are a lot of ways to delete elements in the collection, but is that pop function serious? It's too random to remove elements randomly.
Because the collection is unordered, there is no way to use subscripts to get the elements of the collection, and there is no way to get values through key like a dictionary. This is super awkward. It seems that a collection, like a collection, can only store data, not fetch data.
3. Operation of a set
Intersection and union are easy to understand, difference set is a relative concept, set 1 is different from set 2 difference set and set 2 relative set difference set, which requires special attention. So the symmetric difference can be understood as the part composed of non-intersecting elements.
4. The inclusion relation of a set
Several relationships of sets: intersecting / disjoint, including / not including (relatively speaking). The isdisjoint function determines that it is disjoint and returns True if it does not intersect.
At this point, I believe you have a deeper understanding of "Python3 collection set entry basic knowledge points", might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.