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

[Python basics] the 11th data type built-in method 02

編輯:Python

The content of this chapter is summarized

List built-in methods

Dictionary built in method

Tuple built-in method

Set built-in methods

Variable type and immutable type

This chapter is detailed

1. List built-in methods list

The list does not produce new values after calling the built-in method

1.1 Count the number of data values in the list

l1 = ['jason', 'kevin', 'oscar', 'tony', 'jerry']
l2 = [77, 22, 55, 33, 44, 99]
# Count the number of data in the list
print(len(l1)) # 5
print(len(l2)) # 6

2. increase

2.1 Append data value to the tail append() No matter what data type is written in brackets All of them are regarded as a data value increase

# 2.1 Append data value to the tail append() No matter what data type is written in brackets Are added as a data value 
res = l1.append('owen')
print(res) # None empty
print(l1) # ['jason', 'kevin', 'oscar', 'tony', 'jerry', 'owen']

s1 = '$hello$'
res1 = s1.split('$')
print(res1) # ['', 'hello', '']
print(s1) # $hello$
l1.append([1, 2, 3, 4, 5])
print(l1) # ['jason', 'kevin', 'oscar', 'tony', 'jerry', [1, 2, 3, 4, 5]]

2.2 Insert data values anywhere insert In brackets i And what data types All of them are regarded as a data subset

# Insert the data value at the desired position insert() No matter what data type is written in brackets Are inserted as a data value 
l1.insert(0, [1, 2, 3])
print(l1) # [[1, 2, 3], 'jason', 'kevin', 'oscar', 'tony', 'jerry']
l2.insert(0, ' Jump the queue ') # [' Jump the queue ', [1, 2, 3], 'jason', 'kevin', 'oscar', 'tony', 'jerry']
print(l2)

2.3 Extended list

The way 1

# 2.3 Extended list 
new_1 = [11, 22, 33, 44, 55]
new_2 = [1, 2, 3]
# The way 1
for i in new_1:
new_2.append(i)
print(new_2) # [1, 2, 3, 11, 22, 33, 44, 55

The way 2

# The way 2
print(new_1 + new_2) # [11, 22, 33, 44, 55, 1, 2, 3]

The way 3( Recommended )  extend

# The way 3( Recommended )
new_1.extend(new_2) # The brackets must support for The data type of the loop for loop +append()
print(new_1) # [11, 22, 33, 44, 55, 1, 2, 3]

3. Query data and modify data

# 3. Query data and modify data 
print(l1) # ['jason', 'kevin', 'oscar', 'tony', 'jerry']
print(l1[0]) # jason
print(l1[1:4]) # ['kevin', 'oscar', 'tony']
l1[0] = 'jasonNM'
print(l1) # ['jasonNM', 'kevin', 'oscar', 'tony', 'jerry']

4. Delete data

4.1 Common data policy

# 4.1 Common data policy 
del l1[0] # Through the index
print(l1) # ['kevin', 'oscar', 'tony', 'jerry']

4.2 Deleting by name remove

# 4.2 Delete by name 
res = l1.remove('jason') # Clear data values must be filled in brackets
print(l1, res) # ['kevin', 'oscar', 'tony', 'jerry'] None

4.3 Take out the value first In the delete   pop

# 4.3 Take out the data value first And then delete 
res = l1.pop() # By default, the data value at the end of the list is retrieved And then delete
print(l1, res) # ['jason', 'kevin', 'oscar', 'tony'] jerry
res = l1.pop(0)
print(res, l1) # jason ['kevin', 'oscar', 'tony']

5. Look at the index values index

# 5. View the index value of the data value 
print(l1.index('jason'))

6. Statistics on the occurrence of a certain data value append

# 6. Count the number of occurrences of a data value 
l1.append('jason')
print(l1.count('jason')) # 2

7. Sort sort Ascending   sort(reverse=True)  Descending     b.sort(key=a.index)  duplicate removal b Press a List sort for

l2.sort() # Ascending [22, 33, 44, 55, 77, 99]
print(l2)
l2.sort(reverse=True) # Descending 
print(l2) # [99, 77, 55, 44, 33, 22]

8. Flip reverse

l1.reverse() # Fall back and forth 
print(l1) # ['jerry', 'tony', 'oscar', 'kevin', 'jason']

9. Comparison operations

new_1 = [99, 22]
new_2 = [11, 22, 33, 44]
print(new_1 > new_2) # True It is to compare one by one according to the position order

new_1 = ['a', 11]
new_2 = [11, 22, 33, 44]
print(new_1 > new_2) # Different data types cannot be operated directly by default

new_1 = ['a', 11] # a 97
new_2 = ['A', 22, 33, 44] # A 65
print(new_1 > new_2) # True
new_1 = [' you ', 11] # a 97
new_2 = [' I ', 22, 33, 44] # A 65
print(new_1 > new_2) # False

2. Dictionary built in method dict

Dictionaries rarely involve type conversions Are directly defined and used

# Type conversion ( Understanding can ) Dictionaries rarely involve type conversions Are directly defined and used 
print(dict([('name', 'jason'), ('pwd', 123)])) # {'name': 'jason', 'pwd': 123}
print(dict(name='jason', pwd=123)) # {'name': 'jason', 'pwd': 123}

1. In dictionary k:v Key value pairs are unordered

2. Value

# 2. Value operation 
print(info['username']) # It is not recommended to use If the key does not exist, an error will be reported directly
print(info['xxx']) # It is not recommended to use If the key does not exist, an error will be reported directly
print(info.get('username')) # jason
print(info.get('xxx')) # None
print(info.get('username', ' The key does not have a returned value Default return None')) # jason
print(info.get('xxx', ' The key does not have a returned value Default return None')) # The key does not have a returned value Default return None
print(info.get('xxx', 123)) # 123
print(info.get('xxx')) # None

3. A dictionary of key pairs in the   len

print(len(info)) # 3

4. Modifying data info

info['username'] = 'jasonNB' # If the key exists, it is modified 
print(info) # {'username': 'jasonNB', 'pwd': 123, 'hobby': ['read', 'run']}

5. The new data  info

# 5. The new data 
info['salary'] = 6 # If the key does not exist, it is added
print(info) # {'username': 'jason', 'pwd': 123, 'hobby': ['read', 'run'], 'salary': 6}

6. Delete data

The way 1

# The way 1
del info['username']
print(info) # {'pwd': 123, 'hobby': ['read', 'run']}

The way 2

res = info.pop('username')
print(info, res) # {'pwd': 123, 'hobby': ['read', 'run']} jason

The way 3

# The way 3
info.popitem() # Random delete
print(info) # {'username': 'jason', 'pwd': 123}

7. Quick access key value Key value pair data

print(info.keys()) # Get all the dictionary's k value The result can be regarded as a list dict_keys(['username', 'pwd', 'hobby'])
print(info.values()) # Get all the dictionary's v value The result can be regarded as a list dict_values(['jason', 123, ['read', 'run']])
print(info.items()) # Get the dictionary kv Key value pair data Organize into list tuples dict_items([('username', 'jason'), ('pwd', 123), ('hobby', ['read', 'run'])])

8. Modify dictionary data If the key exists, it is modified If the key does not exist, it is added

# 8. Modify dictionary data If the key exists, it is modified If the key does not exist, it is added 
info.update({'username':'jason123'})
print(info) # {'username': 'jason123', 'pwd': 123, 'hobby': ['read', 'run']}
info.update({'xxx':'jason123'})
print(info) # {'username': 'jason123', 'pwd': 123, 'hobby': ['read', 'run'], 'xxx': 'jason123'}

9. Quickly construct a dictionary Given a value, by default, all keys use a

# 9. Quickly construct a dictionary Given a value, by default, all keys use a 
res = dict.fromkeys([1, 2, 3], None)
print(res) # {1: None, 2: None, 3: None}
new_dict = dict.fromkeys(['name', 'pwd', 'hobby'], []) # {'name': [], 'pwd': [], 'hobby': []}
new_dict['name'] = []
new_dict['name'].append(123)
new_dict['pwd'].append(123)
new_dict['hobby'].append('read')
print(new_dict) # {'name': [123], 'pwd': [123, 'read'], 'hobby': [123, 'read']}

res = dict.fromkeys([1, 2, 3], 234234234234234234234)
print(id(res[1])) # 2340954113104
print(id(res[2])) # 2340954113104
print(id(res[3])) # 2340954113104

10. If the key exists, get the value corresponding to the key If the key does not exist, set And return the new value set

3. Tuple built-in method tuple

# keyword tuple
# Type conversion Support for All data types of a loop can be converted to tuples
print(tuple(123)) # Can not be
print(tuple(123.11)) # Can not be
print(tuple('zhang')) # Sure
t1 = () # tuple
print(type(t1))
t2 = (1) # int
print(type(t2))
t3 = (11.11) # float
print(type(t3))
t4 = ('jason') # str
print(type(t4))

When there is only one data value in a tuple Commas cannot be omitted , If you omit The data type in the brackets is the data type
Suggest : Write tuples Comma plus Even if there is only one data (111, ) ('jason', )ps: In the future, you will encounter data types that can store multiple data values If there is only one data The comma also took the opportunity to add

t2 = (1,) # tuple
print(type(t2))
t3 = (11.11,) # tuple
print(type(t3))
t4 = ('jason',) # tuple
print(type(t4))

1. Count the number of tuples

t1 = (11, 22, 33, 44, 55, 66)
# 1. Count the number of data values in the tuple
print(len(t1)) # 6

2. Check and correct

# 2. Check and correct 
print(t1[0]) # You can check 11
t1[0] = 222 # It can't be changed
""" The index of tuples cannot change the bound address """

t1 = (11, 22, 33, [11, 22])
t1[-1].append(33)
print(t1) # (11, 22, 33, [11, 22, 33])

4. Set built-in methods set

set() Type conversion Support for Cyclic And the data must be immutable
1. To define an empty collection, you need to use keywords
2. Data in a collection must be of immutable type ( integer floating-point character string Tuples Boolean value )

3. duplicate removal

# duplicate removal 
s1 = {1, 2, 12, 3, 2, 3, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 4, 5, 4, 5, 4}
print(s1) # {1, 2, 3, 4, 5, 12}
l1 = ['jason', 'jason', 'tony', 'oscar', 'tony', 'oscar', 'jason']
s2 = set(l1)
l1 = list(s2)
print(l1) # ['jason', 'tony', 'oscar']

4. Simulate two people's friend collection

1. seek f1 and f2 Our mutual friends

f1 = {'jason', 'tony', 'oscar', 'jerry'}
f2 = {'kevin', 'jerry', 'jason', 'lili'}
# 1. seek f1 and f2 Our mutual friends
print(f1 & f2) # {'jason', 'jerry'}

2. seek f1/f2 Unique friends

print(f1 - f2) # {'oscar', 'tony'}
print(f2 - f1) # {'lili', 'kevin'}

3. seek f1 and f2 All friends

print(f1 | f2) # {'jason', 'kevin', 'lili', 'oscar', 'jerry', 'tony'}

4. seek f1 and f2 Their own unique friends ( Exclude common friends )

print(f1 ^ f2) # {'kevin', 'lili', 'tony', 'oscar'}

5. Superset A subset of

# 5. Superset A subset of 
s1 = {1, 2, 3, 4, 5, 6, 7}
s2 = {3, 2, 1}
print(s1 > s2) # s1 Whether it is s2 A set of parent s2 Is it right? s1 Subset
print(s1 < s2)

5. Variable type and immutable type

Why do string calls to built-in methods generate new values The list calls built-in methods to change itself

1. Variable type   list   Value change ( Built-in methods ) The memory address can remain unchanged

# Why do string calls to built-in methods generate new values The list calls built-in methods to change itself 
# 1. Variable type list Value change ( Built-in methods ) The memory address can remain unchanged
l1 = [11, 22, 33]
print(id(l1)) # 1359453669056
l1.append(44) # [11, 22, 33, 44]
print(id(l1)) # 1359453669056

2. Immutable type str int float Value change ( Built-in methods ), The memory address must have changed

# 2. Immutable type str int float Value change ( Built-in methods ), The memory address must have changed 
s1 = '$hello$'
print(id(s1)) # 2807369626992#
s1 = s1.strip('$')
print(id(s1)) # 2807369039344
ccc = 666
print(id(ccc)) # 2807369267664
ccc = 990
print(id(ccc)) # 2807374985904

Homework

# 1.
# Use the list to write an employee name management system
# Input 1 Execute the function of adding user name
# Input 2 Perform the view all user names function
# Input 3 Execute the function of deleting the specified user name
# ps: Think about how to make the program loop and perform different operations according to different instructions
# Tips : Loop structure + Branching structure
# Elevation : Whether it can be replaced by dictionary or nested use of data to complete more perfect employee management rather than a simple user name ( It doesn't matter if you can write )

# 2. Remove the following list and keep the original order of data values
# eg: [1, 2, 3, 2, 1]
# After de duplication [1, 2, 3]

l1 = [2, 3, 2, 1, 2, 3, 2, 3, 4, 3, 4, 3, 2, 3, 5, 6, 5]
l2 = list(set(l1)) # Replace the list with a set, and then replace it with a list
l2.sort(key=l1.index) # Sort the de duplicated list according to the original list
print(l2)

3. There are two sets ,pythons It's registration python A collection of student names for the course ,linuxs It's registration linux A collection of student names for the course
pythons = {'jason', 'oscar', 'kevin', 'ricky', 'gangdan', 'biubiu'}
linuxs = {'kermit', 'tony', 'gangdan'}

1. Find out and sign up python Sign up again linux A collection of student names for the course

print(pythons & linuxs)

2. Find out the name set of all registered students

print(pythons | linuxs) # {'kevin', 'gangdan', 'jason', 'biubiu', 'kermit', 'tony', 'ricky', 'oscar'}

3. Only sign up python The names of the participants in the course

print(pythons - linuxs) # {'kevin', 'oscar', 'ricky', 'jason', 'biubiu'}

4. Find out the students' name set without the two courses at the same time

print(pythons ^ linuxs) # {'biubiu', 'tony', 'kermit', 'jason', 'ricky', 'oscar', 'kevin'}

【python Basics 】 The first 11 return Data type built-in methods 02 More articles about

  1. python Basic grammar 18 Class's built-in methods ( Magic methods ), The singleton pattern

    Class's built-in methods ( Magic methods ): It is usually defined inside a class , With __ start __ The way to end , Are built-in methods of classes , Also called magic method . Class's built-in methods , It will automatically trigger when certain conditions are met . The built-in method is as follows : __new__: stay __ini ...

  2. python for loop while Loop data type built-in methods

    while Conditions : The sub code block executed by the loop after the condition is established Each time the subroutine of the loop body is executed, it will re judge whether the condition is true If yes, continue to execute the subcode. If not, exit break Used to end this layer cycle ### One :continu ...

  3. python Basic operations and their common built-in methods

    # Variable type : The value has changed , however id No change , Prove that you are changing the original value instead of generating a new value , The original value is of variable type # Immutable type : The value has changed ,id Also follow change , It is proved that a new value is generated instead of changing the original value , The original value is immutable # x=10# print( ...

  4. python Basics - character string (str) Types and built-in methods

    character string -str purpose : It is often used to record descriptive content Define methods : # You can use '','''''',"","""""" Can be used to define ...

  5. python Loop and basic data type built-in methods

    Today is another day full of hope One .python loop 1.wuile And else Continuous use When while Not being critical 'break' In the case of active termination After the normal end of the loop body code, the else The subcode of "" ...

  6. python Introduction to common data type built-in methods

    Have a good command of python Common data type built-in method is an internal skill that every beginner must possess . Here's how python Common types of centralized data and their methods , Open source code , The main methods are annotated in Chinese . One . integer a = 100 a.xx ...

  7. python Built in methods for other data types in

    Supplement the built-in method of string data type 1. Remove the specified characters at the beginning and end of the string to select the direction 1: s1 = '$$$jason$$$' print(s1.strip('$')) # jason print(s1.lstrip ...

  8. python- Dictionary data type built-in methods

    Dictionary data type built-in methods ( Compulsory examination ) purpose : Save multiple values , Do not take values by index , You can use keywords to find the corresponding values Define the way :{} Internal to key:value To store multiple values , Values are separated by commas lis = ['ruixing', ...

  9. python Data type built-in methods

    Contents summary List built-in methods Dictionary built in method The method of converting a string into a dictionary eval() Tuple built-in method Tuple related written test questions Set built-in methods List built-in methods l1 = [2, 4, 5, 7, 3, 9, 0, 6] # l ...

  10. python Data type built-in methods Strings and lists

    1. character string Built in method operation # a = 'qqssf'#1. print(a[-1:]) # Take... By index , Forward from 0 Start , Reverse from -1 Start # print(len(a)) # Take the length # a = 'qqssf'# 2. ...

Random recommendation

  1. App Slimming

    http://www.zoomfeng.com/blog/ipa-size-thin.html https://github.com/ming1016/SMCheckProject

  2. LESS Learning summary

    Before, in the process of work , Yes Less, I haven't summarized my learning experience , Today, I finally have time to tidy up .   Less Learn common reference documents : Less Chinese net http://lesscss.cn/ Quick start | Les ...

  3. jQuery Get and set disabled attribute 、 Background image path

    Before for this unique disabled Property acquisition and setting are confusing , Today's project uses , use attr Can't achieve , So many experiments have shown that : obtain disabled Properties with prop $("#basic_key") ...

  4. dbUtils Basic use of

    dbUtils It's right JDBC Complete encapsulation of , Just import the connection pool , add to sql sentence ,dbUtils You can return result sets in various encapsulation forms . If it's Manual , stay DAO Layer using JDBC Query a statement , The following steps are required : 1 establish C ...

  5. 201421123059 http://www.cnblogs.com/deng201421123059/

    201421123059 http://www.cnblogs.com/deng201421123059/

  6. Minimum spanning tree Prim poj1258 poj2485 poj1789

    poj:1258 Agri-Net Time Limit: 1000 MS Memory Limit: 10000 KB 64-bit integer IO format: %I64d , %I64u ...

  7. jdk8 lambda Expression summary

    Java8 lambda expression 10 Example   1. Realization Runnable Thread cases Use () -> {}  Instead of anonymous classes : //Before Java 8: new Thread(new Runnab ...

  8. openssh Compile the overlay installation based on the source code

    Covered , Is to unload the old openssh, Clean the house and treat again ... Be careful : Please do the test well 00. View the installed on this computer openssh rpm –qa |grep openssh rpm -e openssh-s ...

  9. Discover viewports ( window ) Adaptive new world !!vw、vh

    Engaged in front-end has been 1 Years. , I have been worrying about the background adaptation spreading all over the screen , Because we have to adapt to different pc Monitor , So the height cannot be written dead , But write (height:100%) It doesn't work , I'm so worried ~ I don't have to write it css Implement the framework or write it yourself j ...

  10. Multiple desktops Deskspace How to use

    1 to Deskspace Set the background . stay DeskSpace Set the display background to sky box image in options ( The image effect of the software , You can also use still images , That's my own picture ) 2 Set up a background for each of the six desktops ( You can also use the same background ) Right click ...


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