2-13 set type

How to find out who bought the same time IPhone7 and 8?

iphone7 = ['alex','rain','jack','old_driver']
iphone8 = ['alex','shanshan','jack','old_boy']

both_list = []

for name in iphone7:
   if name in iphone8:
       both_list.append(name)

print(both_list)
        

 

Is a set of unordered not repeated combinations of data, its main role is as follows:

  • De-emphasis, the list becomes a collection, automatically go heavy
  • Relationship test, the intersection of the two groups before the test array, poor, union relations, etc.
S = {1,2,3,2,4,5 >>> } # create collections
 >>> S 
{ . 1, 2,. 3,. 4,. 5 } only a # 2
 >>> 
>>> s.add ( 2 ) add duplicate # 2 can not be put into
 >>> s.add (44 is )
 >>> S 
{ . 1, 2,. 3,. 4,. 5, 44 is }
 >>> s.update ([2,3,4 , 5,5,99 ]) # were added to the collection of a plurality of values
 >>> S 
{ . 1, 2,. 3,. 4,. 5, 99, 44 is }
 >>> s.discard (. 1 ) # remove elements, also not no error
 >>> s.pop () # delete a random element is empty, the collection being given
 2 
>>> s.pop ()
 . 3 
>>> S 
{ . 4,. 5, 99, 44 is }
 >>>

>>> s.clear () # Empty
>>> S
SET ()
>>> s.add (. 1)
>>> s.copy ()
{}. 1
>>> s.add ([l, 2,3 ]) # immutable data can add
Traceback (MOST Recent Last Call):
File "<stdin>", Line. 1, in <Module1>
TypeError: unhashable type: 'List'                                                         

 

Set relationship test

  • Intersection
  • Difference set
  • Union

>>> iphone7 = {'alex','rain','jack','old_driver'}
>>> iphone8 = {'alex','jack','shanshan','old_boy'}

Union

>>> iphone7.intersection(iphone8)
{'jack', 'alex'}
>>> iphone7 & iphone8
{'jack', 'alex'}

Difference set

>>> iphone7.difference(iphone8)
{'rain', 'old_driver'}
>>> iphone7 - iphone8
{'rain', 'old_driver'}

Union

>>> iphone8.union(iphone7)
{'old_boy', 'jack', 'shanshan', 'rain', 'old_driver', 'alex'}
>>> iphone8 | iphone7
{'old_boy', 'jack', 'shanshan', 'rain', 'old_driver', 'alex'}

 

Symmetric difference: only buy or only bought iphone8 iphone7 person, and taking the difference counter set

>>> iphone8.symmetric_difference(iphone7)
{'old_boy', 'rain', 'shanshan', 'old_driver'}
>>> iphone8 ^ iphone7
{'old_boy', 'rain', 'shanshan', 'old_driver'}
>>>

 

Inclusion relation

in, not in: == determine whether the elements in the collection! Analyzing two sets are equal =

Usually between two sets of three relationships, intersection, comprising disjoint.

set.isdisjoint (s): Analyzing two sets are not disjoint

set.issuperset (s): determining a set of other sets is not contained, it is equivalent to a> = b

set.issubset (s): determined set is not part of the other set, and so on for a <= b

>>> s
{1, 2, 3, 4}
>>> s2
{2, 3, 5, 6}
>>> s2.add(1)
>>> s2.add(4)
>>> s2
{1, 2, 3, 4, 5, 6}
>>> s.issubset(s2)
True
>>> s2.issuperset(s)
True
>>>

Guess you like

Origin www.cnblogs.com/echo-kid-coding/p/11222943.html