程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python learning 2 (list, tuple, dictionary, set)

編輯:Python

Qianfeng education in b The course of the station , Learning notes

list list

Define the format of the column :[ Elements 1, Elements 2, Elements 3, …, Elements n]

Variable tmp The type of is list
tmp = [‘xiaoWang’,180, 65.0]
The elements in the list can be of different types
List slicing is the same as string

Additive elements

append The new element is added to the end of the list
insert(index, object) At a designated location index Insert element before object
adopt extend You can add elements from another collection to the list one by one , It can also be done through + Number

list1 = ['a','b','c']
list2 = ['d','e']
list1 = list1 + list2
print(list1) #['a', 'b', 'c', 'd', 'e']

Remove elements

The common ways to delete list elements are :

del: Delete according to subscript , Or delete the whole list directly ( Directly delete the variable pointer , Variable names are garbage collected )
pop: Delete the last element , Or delete the elements in the list according to the subscript
remove: Delete based on the value of the element , If there are several same values , Then only delete the first one from left to right
clear: Empty list elements ( Memory not freed )

use for Attention should be paid to when deleting circularly , Deleting the subscript of element traversal will not change , Therefore, there may be omissions

movieName = [' Pirates of the Caribbean ',' The matrix ',' First Blood ',' The Lord of the rings ',' The Hobbit ',' Fast and furious ']
print('------ Before deleting ------movieName=%s' % movieName)
del movieName[2]
print('------ After deleting ------movieName=%s' % movieName)

Delete consecutive identical elements
If you write it normally, delete it like this , There will be problems.

list3 = [1,1,3,1,1,5]
for i in list3:
if i == 1:
list3.remove(i)
print(list3) # [3, 1, 1, 5]

This is because when traversing, we use subscripts to traverse list3 All elements in , If deleted later , The subscript is still appended 1, And the list gets smaller , So we will skip the continuous same elements

But the following operation is feasible , because list3[::] It is equivalent to creating a new list , Traversal is not list3 The elements in , It's the elements in the new list , The new list is the same as the original list , So this deletion is feasible

list3 = [1,1,3,1,1,5]
for i in list3[::]:
if i == 1:
list3.remove(i)
print(list3)

lookup

Judge whether it exists in、not in
in( There is ), If it exists, the result is true, Otherwise false
not in( non-existent ), If not, the result is true, otherwise false
index Used to find the location of the element , If it is not found, an error will be reported ;
count Used to calculate the number of occurrences of an element .
Their use is consistent with that in the string .

>>> a = ['a', 'b', 'c', 'a', 'b']
>>> a.index('a', 1, 3) # Notice that it's left closed right open 
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'a' is not in list
>>> a.index('a', 1, 4)
3
>>> a.count('b')
2
>>> a.count('d')
0

modify

Just change it with subscript

Sort flip

sort The method is to list Rearrange in a specific order , Default is from small to large , Parameters reverse=True It can be changed to reverse order , From big to small .
reverse The method is to list Inversion .

Exchange the values of two variables

In addition to using the third intermediate variable ,python You can directly use the following methods to exchange
a,b = b,a

List derivation

So called list derivation , That's the lightweight loop that creates lists

The basic way

a = [x for x in range(3,6)]
# [3, 4, 5]

Use... In a loop if

a = [x for x in range(9) if x % 2]
# [1, 3, 5, 7]
# Use if And list derivation 
list1 = ['hello', 'hi', 'too','high','88']
list2 = [word.title() if word.startswith('h') else word.upper() for word in list1]
print(list2) # ['Hello', 'Hi', 'TOO', 'High', '88']

The use of multiple for Loop creation

a = [(x,y,z) for x in range(1,3) for y in range(2) for z in range(3)]
# [(1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2)]
a = [x for x in range(1,101)]
b = [a[x:x+3] for x in range(0,len(a),3)]
# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], ...]

Copy of list

As mentioned before , If only with list2 =list1 Copy a list , Just will list2 The pointer to this variable points to list1 Memory address of , If you use list2 Modify the contents in the list ,list1 It will change
namely :Python All assignment operations in are references ( Memory address ) The transfer . For variable types , Modify the value of the original data , Will change the value of the assignment object .

Use list's copy Method

Use list's copy Method , You can directly copy the original list , Become a new list , This replication method is shallow copy .

nums1 = [1, 5, 8, 9, 10, 12]
nums2 = nums1.copy() # Of the call list copy Method , You can copy a new list 
nums2[0] = 100
# Modify the data in the new list , It will not affect the data in the original list 
print(nums2) # [100, 5, 8, 9, 10, 12]
print(nums1) # [1, 5, 8, 9, 10, 12]

copy modular

In addition to using lists copy Out of the way ,Python It also provides copy Module to copy an object .copy The module provides two ways of shallow copy and deep copy , They are used in the same way , But the effect of implementation is different .

A shallow copy is a top-level copy of an object , The popular understanding is : Copied references , There's no copy .
As you can see from the following example , Only the top-level reference is copied , When changing the content of the top layer , Not the original words1 Replace the elements in , And on the inside , That is, when the elements of the second level list are modified ,yes Turned into no

import copy
words1 = ['hello', 'good', ['yes', 'ok'], 'bad']
# Shallow copy only copies the outermost objects , The data inside will not be copied , It's directed at 
words2 = copy.copy(words1)
words2[0] = ' Hello '
words2[2][0] = 'no'
print(words1) # ['hello', 'good', ['no', 'ok'], 'bad']
# wrods2 Inside yes It was modified to no
print(words2) # [' Hello ', 'good', ['no', 'ok'], 'bad']

Deep copy is a recursive copy of all levels of an object .
use deepcopy Copying is copying everything inside , So when modifying the copy object , Will not affect the original content

import copy
words1 = ['hello', 'good', ['yes', 'ok'], 'bad']
# Deep copy will copy all the data in the object 
words2 = copy.deepcopy(words1)
words2[0] = ' Hello '
words2[2][0] = 'no'
print(words1) # ['hello', 'good', ['yes', 'ok'], 'bad']
print(words2) # [' Hello ', 'good', ['no', 'ok'], 'bad']

Slicing is also a light copy

words1 = ['hello', 'good', ['yes', 'ok'], 'bad']
words2 = words1[:]
words2[0] = ' Hello '
words2[2][0] = 'no'
print(words1) # ['hello', 'good', ['no', 'ok'], 'bad']
print(words2) # [' Hello ', 'good', ['no', 'ok'], 'bad']
word3 = ['h', 'a']
print(words1) # ['hello', 'good', ['yes', 'ok'], 'bad']
print(words2) # [' Hello ', 'good', ['h', 'a'], 'bad']

Tuples tuple

Python A tuple of is similar to a list , The difference is that the elements of a tuple cannot be modified . Tuples use braces , Use square brackets for lists .
Accessing tuples also uses subscripts directly , Or use slicing
Look for the element ,index and count
Cannot add 、 Delete 、 Change

Particular attention : Define a tuple with only one element , You need to write a comma after the unique element

>>> aTuple = ('et',77,99.9)
>>> aTuple
('et',77,99.9)
# Particular attention 
t1 = ()
t2 = ('a')
t3 = ('a',)
print(type(t1))
print(type(t2))
print(type(t3))

Conversion of lists and tuples

list(t) take t convert to list
tuple(t) Convert to tuple

t3 = ('a','b')
t3 = list(t3)
print(type(t3)) # list
t3 = tuple(t3)
print(type(t3)) # tuple

Dictionaries

When the stored data needs to be added dynamically 、 When deleting , We usually use lists , But the list sometimes has some trouble . When modifying elements , You need to find the subscript of the element to modify
Using dictionaries , Use key values to In the form of , Store elements , You can modify elements by directly accessing keywords , amount to java Medium map form

Define the format of the dictionary :{ key 1: value 1, key 2: value 2, key 3: value 3, …, key n: value n}

info = {
'name':' Monitor of the class ', 'id':100, 'sex':'f', 'address':' Earth Asia, Shanghai, China '}
info['name'] # The dictionary uses the key to get the corresponding value 

Keys can use numbers 、 Boolean value 、 Boolean value 、 Tuples and other immutable data types , But it's common to use strings
In every dictionary key It's all unique , If there are more than one key, hinder value Will overwrite the previous key Corresponding value
Dictionaries have no subscripts or slices

Check out the elements

Directly use the key to view or use get Method ,
The difference is to use what doesn't exist key Get the corresponding value ,get Method will return None, The former will report an error ;
get You can add the default value

info = {
'name':' Monitor of the class ','age':18}
print(info['age']) # For age 
# print(info['sex']) # Get what doesn't exist key, Exceptions will occur 
print(info.get('sex')) # Get what doesn't exist key, Get empty content , No exceptions . The output is None
print(info.get('sex', ' male ')) # Get what doesn't exist key, You can provide a default value . The output is male , But the default value will not change the dictionary 

Modifying elements

Modify directly through the key

Additive elements

If you are using Variable name [‘ key ’] = data when , This “ key ” In the dictionary , Then overwrite the original value , It is equivalent to modifying elements , non-existent , So it's going to add this element

Remove elements

dict.clear() Empty

dict.pop(key) Delete according to the key , The return value is the value corresponding to the key
dict.popitem() Delete from back to front

d = {
'name':'zs','age':'19'}
r = d.pop('name')
print(d)
print(r) # zs
d = {
'name':'zs','age':'19'}
r = d.popitem()
print(d) # {'name': 'zs'}
print(r) # ('age', '19')

del and pop equally , It can also be based on key Delete , You can also delete the entire dictionary , Will also delete variables

Traverse

for…in… Direct traversal , The return is key

info = {
'name':' Monitor of the class ','age':18, 'sex':'man'}
for d in info:
print(d)
##### Output 
name
age
sex

obtain value,dict.values, The output is a special list

print(info.values())
# Output : dict_values([' Monitor of the class ', 18, 'man'])

obtain key,dict.keys

print(info.keys())
# dict_keys(['name', 'age', 'sex'])

Get every item in the dictionary ,dict.items, The output is the structure of list nested tuples

print(info.items())
# Output :dict_items([('name', ' Monitor of the class '), ('age', 18), ('sex', 'man')])
for k, v in info.items():
print('key:{},value:{}'.format(k, v))
## Output 
key:name,value: Monitor of the class
key:age,value:18
key:sex,value:man

setdefault,update,fromkeys

setdefault It's like adding , Not commonly used , You can only add , It can't be modified
update You can merge two dictionaries

info.setdefault('a','b')
print(info)
# {'name': ' Monitor of the class ', 'age': 18, 'sex': 'man', 'a': 'b'}
dict2 = {
'a':10}
info.update(dict2)
print(info) # {'name': ' Monitor of the class ', 'age': 18, 'sex': 'man', 'a': 10}
print(dict2) # {'a': 10}

fromkeys Create a new dictionary , Call directly with class , The parameter passed is an iteratable object
The output is a new dictionary created , among key Is the value in the first parameter list passed ,value Is the second parameter passed
Not commonly used

dict3 = dict.fromkeys(['a','b'],[10,20])
print(dict3) # {'a': [10, 20], 'b': [10, 20]}

aggregate set

aggregate (set) Is an unordered sequence of non-repeating elements , You can use braces { } perhaps set() Function to create a collection .

Be careful : To create an empty collection, you must use the set() instead of { }, because { } Is used to create an empty dictionary .

Create format :

parame = {
value01,value02,...}
perhaps
set(value)

Additive elements

set.add(x)
perhaps
s.update(x), You can add elements , And the parameter can be a list , Tuples , Dictionary, etc

>>>set1 = set(("Google", "Runoob", "Taobao"))
>>> set1.update({
1,3})
>>> print(set1)
{
1, 3, 'Google', 'Taobao', 'Runoob'}
>>> set1.update([1,4],[5,6])
>>> print(set1)
{
1, 3, 4, 5, 6, 'Google', 'Taobao', 'Runoob'}

Remove elements

s.remove(x)
If you delete something that doesn't exist , Will report a mistake

thisset = set(("Google", "Runoob", "Taobao"))
thisset.remove("Taobao")
print(thisset)
# {'Google', 'Runoob'}
thisset.remove("Facebook") # No errors will occur 
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Facebook'

s.discard(x) Also remove elements from the collection , And if the element does not exist , There will be no errors . The format is as follows :

thisset = set(("Google", "Runoob", "Taobao"))
thisset.discard("Facebook") # No, no error occurs 
print(thisset)
# {'Taobao', 'Google', 'Runoob'}

del You can delete this set directly , After deletion, the variable does not exist
clear Empty , You can still add elements again

set.pop() Randomly delete any element in the set

Intersection, union, subtraction

It can be done in different ways , You can also use the symbol

a = {
1,2,3,4,5}
b = {
4,5,6,7,8,9}
print(a.intersection(b)) # {4, 5}
print(a & b)
print(a.union(b)) # {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(a|b)
print(a.difference(b)) # {1, 2, 3}
print(a- b)

Other supplements

Type conversion

list–> tuple、set( The length may change )
tuple–>set、list
set–>tuple、list

Dictionary to list 、 Tuples 、 aggregate , Just the conversion key

info = {
'name': ' Monitor of the class ', 'age': 18, 'sex': 'man'}
print(list(info)) # ['name', 'age', 'sex']
print(tuple(info)) # ('name', 'age', 'sex')

list 、 Tuples 、 Collections generally cannot be converted to dictionaries
Under special circumstances, you can turn

list2 = [[1,2],[3,4]]
print(dict(list2)) # {1: 2, 3: 4}

Traversal with subscript

All iteratable objects can use enumerate The built-in class is wrapped into a enumerate object . Yes enumerate Traversal , You can get the subscript and element of an iteratable object at the same time

nums = [12, 9, 8, 5, 4, 7, 3, 6]
# Will list nums Package as enumerate object 
for i, num in enumerate(nums): # i Indicates the element subscript ,num Represents the elements in the list 
print(' The first %d The element is %d' % (i, num))

Arithmetic operators for iteratable objects

Format output

Besides using format, You can also use the following form :
python Of print The string is preceded by f Represents a formatted string , Add f Variables and expressions enclosed in curly braces can be used in the string , If there is no expression in the string , So do you add it in front f The output should be the same .
The formatted string literal prefix is ’f’ Similar to the accepted format string str.format(). They contain replacement areas surrounded by curly braces . The replacement field is an expression , Evaluate at run time , And then use format() Format the protocol .

Pay special attention to the difference between inner and outer quotation marks

info = {
'name': ' Monitor of the class ', 'age': 18, 'sex': 'man'}
print(f"name:{
info['name']}") # name: Monitor of the class 

Public methods

print() input() type() id() len()
bin() oct() hex()
chr() to ascill Code to character
ord() Transfer characters ascill code
max() min() sum() abs()
sorted() You can sort iteratable objects , Return a list , adopt reverse=True In descending order


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved