List List = [1, 2, 3] an ordered list with variable element values
Create an empty list:
List=[]
Additions, deletions and modifications:
List.append(4) [1, 2, 3, 4]
List.extend([5,6]) [1, 2, 3, 4, 5, 6]
List.insert(1, 5) [1, 5, 2, 3, 4, 5, 6]
List.pop() [1, 5, 2, 3, 4, 5]
List.pop(1) [1, 2, 3, 4, 5]
List.remove(3) [1, 2, 4, 5]
List[1]=6 [1, 6, 4, 5]
Both append and extend insert at the end of the list. If you want to specify the position, you need to use insert(subscript, content)
pop (subscript) will pop up a return value. If you don’t need to get the deleted value, you can also use: del List[subscript]
To delete a known element, use remove(element value), but it needs to be judged when using it.
Tuple = (1, 2, 3) an ordered list that is immutable after initialization
Create an empty tuple:
tuple = ()
Declaration when there is only one element:
tuple = (1,)
Variable type elements in tuple:
tuple = ('a', 'b', ['A', 'B'])
t[2][0] = 'X' ('a', 'b', ['X', 'B'])
The pointed list has not been changed to another list, and the elements of the list are still variable
Tuples operate similarly to lists.
Dictionary dict = {'a': 1, 'b': 2, 'c': 3}
Key-value (key-value) storage; the key is unique, non-repeatable and immutable; unordered tables have no indexes
Create an empty collection:
dist = {}
If the key is duplicated, the others will be overwritten, and only one will be kept:
dict2 = {"name":"Zhang Wuji","age":20,"name":"Zhang Sanfeng"} {"name":"Zhang Sanfeng","age":20}
Addition and deletion check:
dict1['d']=4 {'a': 1, 'c': 3, 'b': 2, 'd': 4}
dict1.setdefault('d',5) {'a': 1, 'c': 3, 'b': 2, 'd': 4}
dict1.pop('b') {'a': 1, 'c': 3, 'd': 4}
dict1['c'] 3
dict1['e'] reports KeyError: 'e'
dict1.get('c') 3
dict1.get('e') None
dict1.get('e',6) {'a': 1, 'c': 3, 'd': 4, 'e': 6}
dict1['d']=4 If there is no key d, it will be added, and if there is a key d, it will be rewritten. dict1.setdefault('d', 5) will add if there is no key d, and will not do anything if there is a key d.
get('e') will not report an error if it is not found, and will output None. get('e',6) assigns a value of 6 if it cannot be obtained, but does not change the original dictionary.
Check if the key exists:
'e' in dict1 False
dict1.get('e') None
dict1.get('e', "does not exist") does not exist
dict1.get('c') 3
Traverse the key-value of the dictionary:
for x,y in enumerate(dict1): 输出:a 1 c 3 d 4
print(x,y,end=" ")
Set set = {1, 2, 3}
The only difference between set and dict is that the corresponding value is not stored; deduplicated unordered list
Empty collections must use the set function:
set3=set()
If you do not define an empty collection, it will be defined as a dictionary:
set4={}
print(type(set4)) <class 'dict'>
Non-empty set definition:
sets1 = {1 , 2 , 3 }
set2 = set([1, 2, 3]) converts the list into a set
set1[1] TypeError: 'set' object does not support indexing There is no subscript in the set, and the data is stored out of order
Additions and deletions:
set1.add(4) set([1, 2, 3, 4])
set1.remove(2) set([1, 3, 4])
set1.remove(5) reports KeyError: '5'
set1.discard(5) will not report an error
Operation:
set1 - set2 差集 set([4]) set1.difference(set2)
set1 | set2 union set([1, 2, 3, 4]) set1.union(set2)
set1 & set2 intersection set([1, 3]) set1.intersection(set2)
set1 ^ set2 symmetric difference set([2, 4]) set1.symmetric_difference(set2)
Both discard and remove can be used to delete elements in the set. The difference is that if the element of remove is not in the set, an error will be reported, but discard will not.
iterate over (list, tuple, dictionary)
General traversal:
for i in animals: traverse list elements
for index,animal in enumerate(animals): traverse subscript + element
animals =['cat','dog','bee','donkey','horse']
for animal in animals:
print(animal,end=" ")
print()
for index,animal in enumerate(animals):
print(index,":",animal)
print()
output:
Dictionary traversal:
for k in emp: the key of the dictionary
for k in emp.keys(): the key of the dictionary
for k in emp.values(): the value of the dictionary
for k,v in emp.items(): the key and value of the dictionary
for index, k in emp.enumerate(): the subscript of the dictionary, the key
# 字典的遍历
emp = {"name":"王大力","sex":"男","age":36}
for k in emp:
print(k)
print()
# 键
for k in emp.keys():
print(k)
print()
# 值
for v in emp.values():
print(v)
print()
# 键值对
for k,v in emp.items():
print(k,v)
print()
# 下标和键
for k,v in enumerate(emp):
print(k,v)
print()
# 获取字典的所有键和值
emp = {"name":"王大力","sex":"男","age":36}
print(emp.keys())
print(emp.values())
output:
try the code
#coding=utf-8
# 列表
List1 = [1, 2, 3]
List1.append(4)
print List1 # [1, 2, 3, 4]
List1.insert(1, 5)
print List1 # [1, 5, 2, 3, 4]
List1.pop()
print List1 # [1, 5, 2, 3]
List1.pop(1)
print List1 # [1, 2, 3]
List1[1]=6
print List1 # [1, 6, 3]
# 元组
tuple0 = (1)
print type(tuple0) # <type 'int'>
tuple1 = (1,)
print type(tuple1) # <type 'tuple'>
tuple2 = ('a', 'b', ['A', 'B'])
tuple2[2][0] = 'X'
print tuple2 # ('a', 'b', ['X', 'B'])
# 字典
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict1['d']=4
print dict1 # {'a': 1, 'c': 3, 'b': 2, 'd': 4}
dict1.pop('b')
print dict1 # {'a': 1, 'c': 3, 'd': 4}
print dict1['c'] # 3
# print dict1['e'] 报错 KeyError: 'e'
print 'e' in dict1 # False
print dict1.get('e') # None
print dict1.get('e', "不存在") # 不存在
print dict1.get('c') # 3
# 集合
set1 = {1 , 2 , 3}
set2 = set([1 , 2 , 3])
print set1 # set([1, 2, 3])
print set2 # set([1, 2, 3]) 将列表转换成集合
# print set1[1] TypeError: 'set' object does not support indexing 集合中没有下标,是无序存放数据的
set1.add(4)
print set1 # set([1, 2, 3, 4])
set1.remove(2)
print set1 # set([1, 3, 4])
print set1 - set2 # 差集 set([4])
print set1 | set2 # 并集 set([1, 2, 3, 4])
print set1 & set2 # 交集 set([1, 3])
print set1 ^ set2 # 对称差集 set([2, 4])
practise
- L = [[1, 2, 3, 4], ['a', 'b', 'c'], ['x', 'y', 'z'], [['A', 'B'], ['M', 'N']]]
-
- prints out 3
- print a, x
- print out A, M
- Add 9 to L
L = [[1, 2, 3, 4], ['a', 'b', 'c'], ['x', 'y', 'z'], [['A', 'B'], ['M', 'N']]]
print L[0][2]
print L[1][0],L[2][0]
print L[3][0][0],L[3][1][0]
L.append(9)
print L
2. info = {}
-
- Add xiaohua's personal information to a dict, which includes name, age, sex, score
- Get xiaohua's age
- Delete xiaohua's score information
info = {}
info["name"] = "xiaohua"
info["age"] = "18"
info["sex"] = "male"
info["score"] = "100"
print info.get("age")
info.pop("score")
print info
3.
join() function
Syntax: 'sep'.join(seq)
Parameter description
sep: separator. Can be empty
seq: sequence of elements to be connected, strings, tuples, dictionaries The
syntax above is: use sep as a separator to combine all the elements of seq into a new string
Return value: Returns a string generated by connecting each element with the separator sep
os.path.join() function
Syntax: os.path.join(path1[,path2[,...]])
Return value: return after combining multiple paths
Note: parameters before the first absolute path will be ignored
#对序列进行操作(分别使用' '与':'作为分隔符)
>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido
#对字符串进行操作
>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
#对元组进行操作
>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido
#对字典进行操作
>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello
#合并目录
>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'
Reference link: Usage of join() function in Python