Python notes-2_

1. Collection

  1. The elements inside are immutable ! ! ! ! It means you can't save a list, dict in the collection, string, number, tuple and other immutable types can be stored
  2. Born to lose weight, there is no way to save duplicate elements in the collection
  3. Unordered, unlike the list, the index is used to mark the position in the list, the elements are unordered, and the elements in the set are not in order, such as the set {3,4,5} and {3,5,4} Make the same collection-
    the ape circle picked up! !

①-Deduplication

jihe = {1,2,1,3,4,2,3,'testone','testtwo','testone'}

Duplicate values ​​in the collection cannot be stored

Use sets to deduplicate lists

b = [1,3,45,1,2,45,3,5,'jack','jack','rose']
v = set(b)
v
{1, 2, 3, 5, 'jack', 45, 'rose'}    #你set之后,会变成集合
type(v)
<class 'set'>    #这样的最终类型的集合

#我们要把它转换为列表
b = [1,3,45,1,2,45,3,5,'jack','jack','rose']
v = list(set(b))
v
[1, 2, 3, 5, 'jack', 45, 'rose']
type(v)
<class 'list'>

②-Addition and deletion of collection

The collection cannot be modified! ! !

Increase
using add ()

test.add('value')

Delete
Use discard ()

test.discard('value')

Use remove ()

test.remover('velue')


Just check the name directly

'value' in test

③-Relational operation

  1. Intersection #multiple collections with the same value
  2. Union set # In multiple sets, the value is merged and the duplicates are removed
  3. Difference set # (a-b) Output is in set a, but not in set b (b-a) Output is in set b, but there is in set a
  4. Symmetric difference set # is to have all the multiple sets, kick it out, and merge the rest!
s_1024 = {"佩奇","老男孩","海峰","马JJ","老村长","黑姑娘","Alex"}
s_pornhub = {"Alex","Egon","Rain","马JJ","Nick","Jack"}
print(s_1024 & s_pornhub)  # 交集, elements in both set
print(s_1024 | s_pornhub)  # 并集 or 合集
print(s_1024 - s_pornhub)  # 差集 , only in 1024
print(s_pornhub - s_1024)  # 差集,  only in pornhub
print(s_1024 ^ s_pornhub)  # 对称差集, 把脚踩2只船的人T出去

The above is still the intersection of the ape circle
:

Union:

Difference:

Symmetric difference:

Second, the file operation

写:write()

my_file = open('test.txt','w',encoding='utf-8')    #w:是write,写入;encoding是设置编码

my_file.write('这是我写入的内容\n')
my_file.write('Hello World\n')
my_file.write('Python文件读写\n')

my_file.close()    #关闭文件

Read: read ()

file = open('test.txt','r',encoding='utf-8')    #r是只读模式
print(file.readline())  #readline()是只读一行
print(file.readline())  #没读一行,光标会往下走一行
file.close()

print('-----分割线-----\n')

file = open('test.txt','r',encoding='utf-8')
values = file.read()
print(values)
file.close()

Append to write: append
but just change the mode to 'a'

file = open('test.txt','a',encoding='utf-8')

file.write('---这是我追加的内容---')

file.close()

Guess you like

Origin www.cnblogs.com/jzbk/p/12749449.html