Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement the operation of adding, deleting, changing and searching in Python collection

Shulou Source: shulou.com Published: 2022-06-01 06:50:39 10月04日 Update

This article mainly describes how Python collection to achieve add, delete and check operations, the article is very detailed, has a certain reference value, interested friends must read!

1. Set new set element set1 = {'name', 19, 'python'}set1.add ('abc') #Variable set, directly modify the original set print(set1, type(set1))

Return Results:

{'python', 'name', 19, 'abc'}

2. set1.remove ('python ') #removes specified element, if not, returns error print(set1)set1.discard ('name') #removes specified element, if not, returns original set print(set1)set1.pop() #randomly removes a variable set element because the set is out of order print(set1)set1.clear() #empties all elements in variable set print(set 1)del set1 #clears set print(set1)

Return Results:

{'name', 19, 'abc'}

{19, 'abc'}

{'abc'}

set()

NameError: name 'set1' is not defined

3. Modify variable sets

Collection elements are immutable types, so they cannot be modified

4. Collection element query method

Collections cannot be queried by key-value pairs, and they are also unordered without subscripts, so they cannot be queried and can only be traversed.

for i in set1: print(i)#accessing its = iter(set1) #generating iterators print(next(its)) #accessing via next()#or traversing iterators for i in its:print(i)#invariant sets and variable sets are the same traversal operations The above is "Python sets how to achieve add, delete and change search operations" All the contents of this article, thank you for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!

Tags: Element variable query iteration content article result subscript value interest at the same time partner way method more knowledge type industry information Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi MySQL Shulou Information Huawei OPPO Reno