In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "detailed introduction of dict and set in python". In the operation process of actual cases, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!
directory
I. Collections
1. collection definition
2. create a collection
3. deduplication
4. set addition and deletion
5. relational operation
6. sort
7.frozenset
8. practice
9. characteristics
II. Dictionary
1. Dictionary definitions
2. Dictionary printing
3. Delete dictionary elements
4.setdefault
5.defaultdict
I. Collections
1. collection definition
A set is an unordered sequence of non-repeating elements.
2. create a collection
Create a collection using braces { } or the set() function;
To create an empty collection, you must use set() instead of { }
{ } is used to create an empty dictionary.
s = {1,2,3,4}print(s,type(s))
3. print(s,)= {1,2,3,4,3,2,1}
4. Set add delete s = {1,2,3}s.add(4) #single element print(s)s.update({4,5,6}) #multiple elements print(s)s = {1,2,3,4,5,6}s.remove(4) #remove a print(s)s.pop() #remove print(s) randomly
5. Relational operation s1 = {1,2,3}s2 = {1,2,4}print(s1 - s2)print(s1 & s2)print(s1 ^ s2)print(s1| s2)
6. Sort s = {1,6,3,8,5}print(sorted(s))7.frozenset
Frozenset is an immutable version of set, so all methods in set that change the set itself (such as add, remove, discard, xxx_update, etc.) are not supported by frozenset; methods in set that do not change the set itself are supported by fronzenset.
These methods of frozenset function exactly the same as the methods of the same name on set collections. Frozenset has two main functions:
It is safer to use frozenset instead of set when the elements of the set do not need to change.
When some APIs require immutable objects, you must replace set with frozenset. For example, the key of dict must be immutable, so only frozenset can be used; for example, the collection elements of set itself must be immutable, so set cannot contain set, set can only contain frozenset.
s = frozenset({1,2,3})print(s, type(s))
8. practice
Mingming wanted to ask some students to do a questionnaire survey together in school. For the objectivity of the experiment, he first used the computer to generate N random integers between 1 and 1000 (N≤1000). For repeated numbers, only one was retained and the rest of the same numbers were removed. Different numbers correspond to different student numbers. Then sort these numbers from large to small, and find students to do surveys according to the order arranged. Please help Mingming complete the work of "de-duplication" and "sorting"(there may be multiple sets of data in the same test case, I hope you can handle it correctly).
import randoms = set()n = int(input("the count:"))for i in range(n): s.add(random.randint(1,1000))print(sorted(s,reverse=True))9. Characteristic
Connection +, duplicate *, index, slice are not supported
Support in, not in
II. Dictionary
1. Dictionary definitions
Dictionaries are another variable container model and can store any type of object.
Keys are generally unique, and if the last key-value pair is repeated, it replaces the previous one. Values do not need to be unique.
Determine whether the character is in the dictionary. Note that the character here is the content of the key value, not the value.
d = {'name':'jia' , 'age':'18' , 'city':'xian'}print(d,type(d))print('name'in d)print('jia'in d)
2. Dictionary printing
Key, value, dictionary printing
d = {'name':'jia' , 'age':'18' , 'city':'xian'}print(d.keys())print(d.values())print(d.items())print(d['name'])print(d['age'])print(d['city'])
Print value
print(d['name'])print(d['age'])print(d['city'])
According to dictionary format, customize key value and value, get value
print(d.get ('province ', ' shanghai'))
Add and modify dictionary values
d = {'name':'jia', 'age':'18'}d['name'] = 'zhao'print(d)d['city'] = 'xian'print(d)
Cycle printing dictionary contents
for item in d: print(item)for item in d.items(): print(item)
bivariate circular printing dictionary
for k,v in d.items(): print(f'key={k},value={v}')
3. Delete dictionary elements
Method 1: pop () method pops up the specified element
d = {'name':'jia' , 'age':'18' , 'city':'xian'}d.pop('name')print(d)
Method 2: del() method deletes the specified element:
d = {'name':'jia' , 'age':'18' , 'city':'xian'}# d.pop('name')del d['age']print(d)
4.setdefault
Set the default value to the specified value. When the default value is specified, it will not be changed.
d = {'name':'jia' , 'age':'18' , 'city':'xian'}d.setdefault('city','luoyang')print(d)d.setdefault('city','beijing')print(d)
5.defaultdict
collections.defaultdict class, itself provides the function of default values, default values can be plastic, list, collection, etc.
Defaultdict is a subclass of dict. But the biggest difference between it and dict is that if the program tries to access a value based on a non-existent key, it raises a KeyError exception; defaultdict provides a default_factory attribute that automatically generates a default value for a non-existent key.
Requirements:
We want a word that maps a key to multiple values (a so-called one-key multi-value dictionary).
Solution:
1). A dictionary is an associative container in which each key maps to a separate value. If you want the key to map to multiple values, you need to save these multiple values in a container (list or collection).
2). Automatically initialize the first value using the defaultdict class in the collections module, so you only need to focus on adding elements.
from collections import defaultdictd = defaultdict(int)d['num'] += 1print(d)d = defaultdict(list)d['hosts'].append('host1')print(d)d = defaultdict(set)d['media'].add('demo')print(d)
"Python dict and set detailed introduction" content is introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!
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: 218
*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.