python09: collection

A collection set type

1 role

Relational operation, Deduplication

Use for relational operators can do, it is too much trouble.

l1=[1,2,3,4,5]
l2=[3,3,4,5,6]
l=[]
for x in l1:
    if x in l2:
      l.append(x)
      print(x)

2 is defined: {} in the plurality of elements separated by commas, the collection element has three characteristics:

1. the collection of elements are immutable type

2. unordered collection of elements within

3. the set of elements is not repeated

Definition of the empty set: s = set (), braces default empty dictionary.

3 type conversion

set({1,2,3})
res=set('helllllllo')
dict=({'k1':1,'k2':2})
s=set(dict)
print(res,s)

Built Method 4 - Relational Operators

4.1 intersected

friend1={1,2,3,4,5}
friend2={3,4,5,6,7,8}
print(friend1 & friend2)

4.2 Take union

print(friend1 | friend2)

4.3 taking the difference current

print(friend1 - friend2)

4.4 Take symmetric difference

print(friend1 ^ friend2)

4.5 father and son set

When set S1 is a subset of said S2, S1 <S2

Built Method 5 - deduplication

Features: only for immutable types, can not guarantee that the original order.

General to re-write their own programs according to the situation, python can not provide all the solutions to problems

l=[
    {'name':'lili','age':18,'sex':'male'},
    {'name':'jack','age':73,'sex':'male'},
    {'name':'tom','age':20,'sex':'female'},
    {'name':'lili','age':18,'sex':'male'},
    {'name':'lili','age':18,'sex':'male'},
]
new_l=[]
for dic in l:
    if dic not in new_l:
        new_l.append(dic)

6 Other built-in method

6.1 .discard in parentheses is the value you want to delete (), delete the element does not exist if no error

s={1,2,3}
# s.discard(4) # 删除元素不存在do nothing
# print(s)
# s.remove(4) # 删除元素不存在则报错

6.2 .update () to add a new collection, .add () to add a new element

# s.update({1,3,5})
# print(s)
# s.add(4)
# print(s)

6.3 .pop () removes an element of random

# s.update({1,3,5})
# print(s)

Guess you like

Origin www.cnblogs.com/Franciszw/p/12482992.html