Lists, tuples, dictionaries, set the type of built-in method

But also a wonderful start of the week, last week, still in the adaptation period to learn python, although not yet fully adapted, but this week was to enhance learning efforts, and I want more input. Today, built-in method to learn more, need more practice to use more than remember.

First, list the type of built-in method

1. Role:

Represent multiple names, multiple hobbies, many courses, etc.

2, is defined by:

A plurality of spaced apart elements of any data type comma in []

3, built-in method:

Priority grasp

1, according to an index value (positive value and the reverse value), it can also preferably kept

name_list=['yujin','xuchu','dianwei','xiahoudun']
name_list[1]='zyl'   # 存:把xuchu换成了zyl
print(name_list)     # ['yujin', 'zyl', 'dianwei', 'xiahoudun']
print(f"{name_list[1]}")  # 取:zyl 

2, sliced

name_list=['yujin','xuchu','dianwei','xiahoudun']
print(name_list[0:4:2])  # ['yujin', 'dianwei'],2为取值长度,即在首个索引序号加2 
print(name_list[::-1]) # -1为从右到左反向取值,取值长度为1

. 3, len (length)

name_list=['yujin','xuchu','dianwei','xiahoudun']
print(len(name_list))  # 结果为4

4, in / not in (the members of calculation)

For determining whether the output result is True or False

name_list=['yujin','xuchu','dianwei','xiahoudun']
print('houyi'in name_list)      # False
print('houyi'not in name_list)  # True

5, for circulation

name_list=['yujin','xuchu','dianwei','xiahoudun']
for name in name_list:
    print(name)  # 挨个取值,逐行法印列表中的每个元素

6, Append (add)

Add after the last element in the list

name_list=['yujin','xuchu','dianwei','xiahoudun']
name_list.append('xiahouyuan') # 把'xiahouyuan'追加在'xiahoudun'后面
print(name_list)  # ['yujin', 'xuchu', 'dianwei', 'xiahoudun', 'xiahouyuan']

7, del (delete)

name_list=['yujin','xuchu','dianwei','xiahoudun']
del name_list[1]  # 删除索引序号为1的值,即删除'xuchu'
print(name_list)  # ['yujin', 'dianwei', 'xiahoudun']

Need to know

1, COUNT () (an element within the list of counts)

name_list=['yujin','xuchu','dianwei','xiahoudun','xuchu']
print(name_list.count('xuchu'))  # xuchu的计数为2

2, POP () (default delete the last element in the list)

name_list=['yujin','xuchu','dianwei','xiahoudun']
print(name_list.pop()) # 打印删除的元素,默认删除最后一个元素xiahoudun
print(name_list)       # ['yujin', 'xuchu', 'dianwei']
print(name_list.pop(1)) # 也可以删除指定索引序号对应的元素,删除xuchu
print(name_list)       # ['yujin', 'dianwei']

3, the Remove () (remove)

name_list=['yujin','xuchu','dianwei','xiahoudun']
name_list.remove('dianwei') # 移除dianwei,直接print(name_list.remove('dianwei'))的话,打印结果为None
print(name_list)            # ['yujin', 'xuchu', 'xiahoudun']

. 4, INSERT () (insert, inserted in front of an element value corresponding to the specified index number)

name_list=['yujin','xuchu','dianwei','xiahoudun']
name_list.insert(2,'xingtian')  # 在dianwei前插入xingtian
print(f"name_list:{name_list}")   # name_list:['yujin', 'xuchu', 'xingtian', 'dianwei', 'xiahoudun']

5, index () (index) printed results will find a list of index numbers worthy

name_list=['yujin','xuchu','dianwei','xiahoudun']
print(name_list.index('xuchu'))  # 打印xuchu的索引序号:1
print(name_list.index('dianwei',1,3))  # 在索引序号1~3之间查找有没有'dianwei'这个值,打印结果为该值的索引序号,不能索引列表内没有的值

6, the Clear () (Clear) Basic will not be used

name_list=['yujin','xuchu','dianwei','xiahoudun']
name_list.clear()  # 清除列表中所有值
print(f"name_list:{name_list}")   # name_list:[]

7, Copy () (copy)

name_list=['yujin','xuchu','dianwei','xiahoudun']
print(name_list.copy())  # 复制列表,['yujin', 'xuchu', 'dianwei', 'xiahoudun']

8, Extend () (extended list)

name_list=['yujin','xuchu','dianwei','xiahoudun']
name_list2=['xiahouyuan','xuhuang','zhanghe']
name_list.extend(name_list2)  # 在第一个列表最后一个元素后面加上第二个列表,来扩展第一个列表
print(name_list) # ['yujin', 'xuchu', 'dianwei', 'xiahoudun', 'xiahouyuan', 'xuhuang', 'zhanghe']

9, Reverse () (inversion)

name_list=['yujin','xuchu','dianwei','xiahoudun']
name_list.reverse() # 把列表中元素的顺序从后往前反转
print(name_list)    # ['xiahoudun', 'dianwei', 'xuchu', 'yujin']

10, sort () (sorted) list of elements sorted using the sort must be of the same type

name_list=['yujin','xuchu','dianwei','xiahoudun']
name_list.sort()  # 列表中的元素按首字母的顺序从前往后排序,首字母相同的按第二个字母排序
print(name_list)  # ['dianwei', 'xiahoudun', 'xuchu', 'yujin']

s=[1,5,3,4,2]
s.sort()
print(s)  # [1, 2, 3, 4, 5]

4, a stored value or multiple values: a plurality of values

5, ordered or disordered: Ordered

6, variable or immutable: variable

 lis = [1, 1, 2, 3, 4, 5]
 lis2 = []
 for i in lis.copy():
     if lis.count(i) == 1:
         lis2.append(i)

Second, the tuple type built-in method

Ganso and a list of exactly the same, but can not be modified Ganso, Ganso defining moment of his value as well as the number of elements of elements of all fixed up

1, the difference between tuples and lists of

Variable is a list of reasons: the memory address corresponding to the index value may be varied

Tuples can not become the reason is: memory address corresponding to the index value can not change, or conversely, as long as the memory address corresponding to the index value has not changed, then the tuple is always unchanged

2, is defined by: the list [] into ()

3, built-in method: Only index () and count ()

tup = (1,2,3,4)
print(tup.index(1))  # 打印0,1的索引序号为0
print(tup.count(1))  # 打印1, 1的计数为1

4, stored value or a plurality of values: a plurality of values

5, ordered or disordered (order: that is indexed and disorderly: no index): Ordered

6, the variable or non-variable: immutable

Third, the dictionary type built-in method

1, the role:

For value added information is described using a plurality of stored values, but each has a value of a corresponding key, key values ​​described functions. Used for stored value represents a different state, such as the value stored there name, age, height, weight, hobbies

2, is defined by:

{} Separated by commas within the plurality of elements, each element is key: value form, value can be any data type, but generally should be a string type key, but must change the type of key is not available

info_dict={'name':'zyl','age':25,'height':178,'hobby_list':['music','basketball','game']}

3, built-in method:

Priority grasp

1, by the access key value, may also be changed either deposit

info_dict={'name':'zyl','age':25,'height':178,'hobby_list':['music','basketball','game']}
print(info_dict['hobby_list'])  # ['music', 'basketball', 'game']
info_dict['height']=183
print(info_dict)  # {'name': 'zyl', 'age': 25, 'height': 183, 'hobby_list': ['music', 'basketball', 'game']}   身高height的值就由178改为了183

2, len (length)

info_dict={'name':'zyl','age':25,'height':178,'hobby_list':['music','basketball','game']}
print(len(info_dict))      # 该字典长度为4

3, in / not in (membership operator) for the same judgment, the output list with True or False

info_dict={'name':'zyl','age':25,'height':178,'hobby_list':['music','basketball','game']}
print('age'in info_dict)    # True

4, delete

  • To remove the dict del

    info_dict={'name':'zyl','age':25,'height':178,'hobby_list':['music','basketball','game']}
    del info_dict['age']  # 删除列表中的key值为‘age’的元素
    print(info_dict)  # 原列表变为{'name': 'zyl', 'height': 178, 'hobby_list': ['music', 'basketball', 'game']}
  • dict delete the pop ()

info_dict={'name':'zyl','age':25,'height':178,'hobby_list':['music','basketball','game']}
info_dict.pop('height')   # 指定删除key值为‘height’的元素
print(info_dict)  # {'name': 'zyl', 'age': 25, 'hobby_list': ['music', 'basketball', 'game']}
  • del delete the popitem ()

Early days dictionaries are unordered, random deleted, but because of the underlying optimization python3 the dictionary, let's look at the dictionary seemingly orderly, so the default dictionary to delete the last key-value pair

info_dict={'name':'zyl','age':25,'height':178,'hobby_list':['music','basketball','game']}
print(info_dict.popitem())  # 默认删除最后一个元素('hobby_list', ['music', 'basketball', 'game'])

5, for circulation may want to print the results line by line

info_dict={'name':'zyl','age':25,'height':178,'hobby_list':['music','basketball','game']}
for k,v in info_dict.items():     # items(键值对)可以换成keys()、values()
    print(k,v)  # name zyl
                # age 25
                # height 178
                # hobby_list ['music', 'basketball', 'game']

6, key Keys (), the value of values (), on the key-value items () (the most widely used items, together with the general decompression)

info_dict={'name':'zyl','age':25,'height':178,'hobby_list':['music','basketball','game']}
print(info_dict.keys())   # 取出的是key值得元组,dict_keys(['name', 'age', 'height', 'hobby_list'])
print(list(info_dict.keys()))  # 取出的是key值得列表,['name', 'age', 'height', 'hobby_list']
print(info_dict.values())  # 取出value值得元组,dict_values(['zyl', 25, 178, ['music', 'basketball', 'game']])
print(info_dict.items())   # 取出键值对的元组,dict_items([('name', 'zyl'), ('age', 25), ('height', 178), ('hobby_list', ['music', 'basketball', 'game'])])

for i in info_dict.values():
    print(i)   # 逐行打印value值
for i in info_dict.items():
    print(i)   # 逐行打印每个键值对的元组
    

Need to know

. 1, GET () in brackets key, if so, returns the corresponding value Key; if not, the default return None

info_dict={'name':'zyl','age':25,'height':178}
print(info_dict.get('name'))   # 找到有name,就返回name的值zyl
print(info_dict.get('weight') # 没有weight,返回None

2, setDefault () there will not change the specified key value; no specified key value is changed; may be used to resolve duplicate assignment

info_dict={'name':'zyl','age':25,'height':178}
print(info_dict.setdefault('name','dianwei'))  # 字典中有name,就返回name对应的值zyl
print(info_dict.setdefault('name1','dianwei'))  # 没有name1,输出指定的值dianwei
print(info_dict)  # 会在原字典中加入name1的键值对,{'name': 'zyl', 'age': 25, 'height': 178, 'name1': 'dianwei'}

3, Update () to update, add after the last element dictionary

info_dict={'name':'zyl','age':25,'height':178}
dict={'weight':'160'}
info_dict.update(dict) # 在info_dict字典的最后面加入dict中的键值对元素
print(info_dict)    # {'name': 'zyl', 'age': 25, 'height': 178, 'weight': '160'}

4, fromkeys () a . Dict out quickly create a dictionary

dic=dict.fromkeys(['name','age','height'],'zhanshen')  # 造一个字典,括号内列表中每个元素作为key,把zhanshen作为每个key的value值
print(dic)  # {'name': 'zhanshen', 'age': 'zhanshen', 'height': 'zhanshen'}

4, a stored value or multiple values: a plurality of values, the value may be a plurality of types, key must be immutable type, generally should be immutable types string type

5, ordered or disordered: disordered

6, variable or immutable: variable

Fourth, the set type built-in method

1, the role:

Relationship for assembly operations, since the elements in the set unordered collection of elements and can not be repeated, and therefore can be set to the weight, but the weight set to disrupt the order of the original elements.

2, is defined by:

{} The comma-separated plurality of elements, each element must be immutable

s = {1, 2, 1, 'a', 'a', 'c'}
print(s)

s = {} braces is empty dictionary, not a collection, a null set must be defined starting set ()

3, built-in method:

* Priority grasp

. 1, len (length)

2, in / not in (the members of calculation)

. 3, | (vertical bars) or Union (and set) the two sets combined, only a repeating elements in the set of output

pythoners = {'jason', 'nick', 'tank', 'sean'}
linuxers = {'nick', 'egon', 'kevin'}

print(f"pythoners|linuxers: {pythoners|linuxers}")
print(f"pythoners.union(linuxers): {pythoners.union(linuxers)}")

输出:pythoners | linuxers: {'egon', 'tank', 'kevin', 'jason', 'nick', 'sean'}
pythoners.union(linuxers): {'egon', 'tank', 'kevin', 'jason', 'nick', 'sean'}

4, & or intersection (intersection) found two repeated elements set

pythoners = {'jason', 'nick', 'tank', 'sean'}
linuxers = {'nick', 'egon', 'kevin'}

print(f"pythoners&linuxers: {pythoners&linuxers}")
print(f"pythoners.intersection(linuxers): {pythoners.intersection(linuxers)}")

Output: & linuxers pythoners: { 'Nick'}
pythoners.intersection (linuxers): { 'Nick'}

5, - or -difference (set difference) ab &, remove duplicate set with a set of elements b

pythoners = {'jason', 'nick', 'tank', 'sean'}
linuxers = {'nick', 'egon', 'kevin'}

print(f"pythoners-linuxers: {pythoners-linuxers}")
print(f"pythoners.difference(linuxers): {pythoners.difference(linuxers)}")

输出:pythoners-linuxers: {'tank', 'jason', 'sean'}
pythoners.difference(linuxers): {'tank', 'jason', 'sean'}

6, == for determining whether the same two elements of a set, returns a value of True or False

7, ^ or symmetic_difference (symmetric difference) were combined and the two sets of duplicate elements removed

pythoners = {'jason', 'nick', 'tank', 'sean'}
linuxers = {'nick', 'egon', 'kevin'}

print(f"pythoners^linuxers: {pythoners^linuxers}")
print(
    f"pythoners.symmetric_difference(linuxers): {pythoners.symmetric_difference(linuxers)}")

输出:pythoners^linuxers: {'egon', 'tank', 'kevin', 'jason', 'sean'}
pythoners.symmetric_difference(linuxers): {'egon', 'tank', 'kevin', 'jason', 'sean'}

. 8, >,> =, issuperset (parent set) to determine whether the former is a superset of, returns a value of True or False

. 9, <, <=, issubset (subset) to determine whether the latter is a subset of the former, the result returns True or False

10, the Add () were added sequentially

s = {1, 2, 'a'}
s.add(3)
print(s)   # {1, 2, 3, 'a'}

Need to know

1, the Remove () (remove)

s = {1, 2, 'a'}
s.remove(1)
print(s)  # {2, 'a'}

2, difference_update () to the same former in the latter out of the update element, i.e., removed

pythoners = {'jason', 'nick', 'tank', 'sean'}
linuxers = {'nick', 'egon', 'kevin'}
pythoners.difference_update(linuxers)
print(f"pythoners.difference_update(linuxers): {pythoners}")  
 # pythoners.difference_update(linuxers): {'tank', 'jason', 'sean'}

. 3, Update () elements of a collection of post-update to the previous set, and remove duplicate

4, discard () delete elements, delete elements in the collection, it is not the same, nor error, remove elements to be deleted can not find the words will complain

. 5, isdisjoint () determines two sets have no common parts, there is no return True, and False have

4, a stored value or multiple values: a plurality of values, and the value of immutable type

5, ordered or disordered: disordered

6, variable or immutable: variable

The study summarizes the time spent too long, too low efficiency, have more exercise

Guess you like

Origin www.cnblogs.com/zhuangyl23/p/11305734.html