程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

5_ Python advanced_ Set data structure

編輯:Python

set It means a set .
According to the mathematical definition of set ,set Inside Data cannot be duplicate .
example : The check list contains duplicate elements .

# use for Loop to retrieve non repeating elements / data 
inputs = ['red', 'red', 'blue', 'yellow', 'yellow', 'green', 'orange', 'yellow', 'purple']
outputs = []
for item in inputs:
if inputs.count(item) > 1:
if item not in outputs:
outputs.append(item)
else:
pass
else:
pass
print(outputs)

The output is :

['red', 'yellow']

so , It is troublesome to check the repeating elements in the list with a circular method .
When set Data structure time , It will be concise .

# use set data structure , It's simpler 
inputs = ['red', 'red', 'blue', 'yellow', 'yellow', 'green', 'orange', 'yellow', 'purple']
outputs = set([x for x in inputs if inputs.count(x) > 1])
# Go through the list one by one inputs Repeated in the list x value , So the list is repeated , It can be used set Remove the repetition 
print(outputs)

The output is :

{
'red', 'yellow'}

set The data structure is also similar to the mathematical set , There are also intersection and difference operations .
intersection : Data in both sets .
Difference set :⽤⼀ Subtract another set ⼀ A collection of data .

# set Intersection operation 
inputs = ['red', 'red', 'blue', 'yellow', 'yellow', 'green', 'orange', 'yellow', 'purple']
inputs_also = ['yellow', 'brown']
# First of all, put list The data structure is converted into set data structure 
inputs = set(inputs)
inputs_also = set(inputs_also)
print(inputs.intersection(inputs_also))

The output is :

{
'yellow'}

so ,set.intersection() Method to find the intersection .

# set Subtraction operation 
inputs = ['red', 'red', 'blue', 'yellow', 'yellow', 'green', 'orange', 'yellow', 'purple']
inputs_also = ['yellow', 'brown']
# First of all, put list The data structure is converted into set data structure 
inputs = set(inputs)
inputs_also = set(inputs_also)
print(inputs.difference(inputs_also))

so ,set.difference() Method to find difference sets .
set The creation of : You can use list establish , Reuse set() convert to set example ; You can also directly use curly braces to create .

# set establish 
set_instance = {
'a', 15, 13.69, False}
print(type(set_instance))

The output is :

<class 'set'>

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved