Catalog
- 1. The answer to the last issue is
- 2. How to delete a list (list) Repeating elements in
- 3. How to find two lists (list) Intersection 、 Difference set or union set ?
- 4. How to iterate a sequence in reverse order ?
- 5. List sort Methods and sorted What's the difference between the methods ?
- 6. What are the common methods in the list ?
- 7. What is list generation ?
- 8. String formatting % and .format,f What's the difference between formatting strings ?
- 9. Single quotation marks 、 What are the differences between double quotation marks and triple quotation marks ?
- 10. Python What are the common string methods in ?
- 11. How to judge whether a string is all numbers ?
- 12. Python What built-in functions do dictionaries have ?
- 13. Dictionary items() Methods and iteritems() How is the method different ?
- 14. What are the common built-in methods for collections ?
- 15. The real question
If you like to program, you can add some Q Group 867067945, You can get free learning materials when you join the group ! The group is full of friends who want to learn programming
1. The answer to the last issue is
- “1 or 2”、“1 and 2”、“1 < (2==2)”、“1 < 2==2” What to output respectively ? 1 2 False True
- What is the result of running the following code ? “A”
value = "B" and "A" or "C"
print(value)
12
- use 4、9、2、7 Four Numbers , have access to +、-、*、 and /, Use each number once , Let the result of the expression be 24, What is an expression ? ==> (9+7-4)*2
- any() and all() What's the difference ? any() As long as one element in the iterator is true ,all() It is required that all judgment items in the iterator return true , The result is true .
- Python What elements in it are false ? 0 An empty string 、 An empty list 、 An empty dictionary 、 An empty tuple 、None、False All means false .
- stay Python Is there a ternary operator in “?:” ? No, min = a if a<b else b
- How to declare multiple variables and assign values ? a,b,c=3,4,5 a=b=c=3
- Do the following procedures report errors V3 Will report a mistake , Because the key of a dictionary element cannot be a mutable object
v1 = {}
v2 = {3:5}
v3 = {[11,23]:5}
v4 = {(11,23):5}
1234
- a = (1,),b = (1),c = (“1”) What types of data are they ? a For tuples ,b Is an integer ,c For the string , have access to type Function to verify .
- Use for Loop through the list separately 、 Tuples 、 Dictionaries and collections .( Simple )
- 99 What's the octal representation of .print(oct(99)) ==> 0o143
- Please write decimal to binary 、 octal 、 Hexadecimal program .# Get the input decimal number dec = int(input(" Input number : ")) print(" Decimal system : ", dec) print(" Convert to binary to : ", bin(dec)) print(" Convert to octal to : ", oct(dec)) print(" Convert to decimal to : ", hex(dec)) 123456
2. How to delete a list (list) Repeating elements in
There are many ways to remove duplicate elements from a list , Here are five ways to delete them .
Method 1 : Use set (set) The way
elements = ["a", "a", "b", "c", "c", "b", "d"]
e = list(set(elements))
print(e)
123
This method makes use of set Non repeatable properties of the elements in the . besides , If you want to keep the list elements in their original order , So you can use list Class sort Method :
elements = ["a", "a", "b", "c", "c", "b", "d"]
e = list(set(elements))
e.sort(key=elements.index)
print(e) # ['a', 'b', 'c', 'd']
1234
Method 2 : The way to use a dictionary , Use a dictionary key Uniqueness
# The way to use a dictionary , Use a dictionary key Uniqueness
elements = ["a", "a", "b", "c", "c", "b", "d"]
# e = list({}.fromkeys(elements))
e = list({}.fromkeys(elements).keys())
print(e) # ['a', 'b', 'c', 'd']
12345
If you like to program, you can add some Q Group 867067945, You can get free learning materials when you join the group ! The group is full of friends who want to learn programming
This method takes advantage of the fact that the key value of the dictionary can't be repeated . among ,Python function dict.fromkeys(seq[.value]) Used to create a new dictionary , In sequence seq The value of the element in the dictionary ,value Is the initial value of all keys in the dictionary , As shown below :

Method 3 : The way lists are derived
elements = ["a", "a", "b", "c", "c", "b", "d"]
e = []
for i in elements:
if i not in e:
e.append(i)
print(e)
123456
Method four :count Count
elements = ["a", "a", "b", "c", "c", "b", "d"]
n = 0
while n < len(elements):
if elements.count(elements[n]) > 1:
elements.remove(elements[n])
continue
n += 1
print(elements) # ['a', 'c', 'b', 'd']
12345678
Method five :reduce function
from functools import reduce
elements = ["a", "a", "b", "c", "c", "b", "d"]
v = reduce(lambda x, y: x if y in x else x + [y], [[]] + elements)
print(v) # ['a', 'b', 'c', 'd']
12345
3. How to find two lists (list) Intersection 、 Difference set or union set ?
Look for two lists (list) Intersection 、 Difference set or union set , The easiest way to think of is to use for Loop to achieve , As shown below :
a = [1, 2, 3, 4, 5]
b = [2, 4, 5, 6, 7]
# intersection
result = [r for r in a if r in b]
print(f"a And b Intersection : {result}") # a And b Intersection : [2, 4, 5]
# Difference set stay a But not in b in
result = [r for r in a if r not in b]
print(f"a And b The difference between the set : {result}") # a And b The difference between the set : [1, 3]
# Combine
result = a
for r in b:
if r not in result:
result.append(r)
print(f"a And b Union : {result}") # a And b Union : [1, 2, 3, 4, 5, 6, 7]
1234567891011121314
Method 2 : use set operation
a = [1, 2, 3, 4, 5]
b = [2, 4, 5, 6, 7]
# intersection
result = list(set(a).intersection(set(b)))
print(f"a And b Intersection : ", result) # a And b Intersection : [2, 4, 5]
# Difference set stay a But not in b in
result = list(set(a).difference(set(b)))
print(f"a And b The difference between the set : ", result) # a And b The difference between the set : [1, 3]
# Combine
result = list(set(a).union(set(b)))
print(f"a And b Union : ", result) # a And b Union : [1, 2, 3, 4, 5, 6, 7]
123456789101112
4. How to iterate a sequence in reverse order ?
Python The common sequences in are strings 、 Lists and tuples . Reverse the sequence , You can use built-in functions reversed() or range() To achieve , You can also use extended slicing [::-1] In the form of . If the sequence is a list , Then you can also use the list's own reverse() Method .
(1) reversed() yes Python Built in functions , Its parameters can be strings 、 A sequence of lists or tuples .
(2) utilize range() Method to generate the reverse index of the sequence , And then traverse from the last element to the beginning element , You can output the elements of the sequence in reverse order .range(start, end[,step]) Parameter description of the method :
start: Count from start Start . The default is 0 Start .
end: Count to end end , But does not include end.
step: step , The default is 1.
(3) seq[::-1] The extended slicing method makes use of sequence slicing operations , Slicing is an advanced feature of sequences .seq[::-1] Indicates reverse access seq All elements in , And take one at a time .-1 Represents a reverse traversal of the last element of a sequence .
(4) If it's a list (list) Sequence , Then you can also use the list directly reverse() Method . The sample code is as follows :
seq = "Hello World"
# reversed() Built in function method
for s in reversed(seq):
print(s, end="")
print() # Line break
# range() Function method
for i in range(len(seq) - 1, -1, -1):
s = seq[i]
print(s, end="")
print()
# [::-1] Extended slicing method
for s in seq[::-1]:
print(s, end="")
print()
# list Self contained reverse() Method
seq = [1, 2, 3, 4, 5, 6]
seq.reverse()
for s in seq:
print(s, end="")
print()
12345678910111213141516171819202122
5. List sort Methods and sorted What's the difference between the methods ?
Python There are two ways to sort a list , One is self-contained sort(), The other is the built-in method sorted. You can use built-in functions help() Check it out. sort() Method and sorted() A detailed description of the method .
List sort Methods and built-in methods sorted There are key and reverse Parameters , key Parameter receives a function to implement a custom sort , for example key=abs Sort by absolute value .reverse The default value is False, Indicates that there is no need to reverse sort , If you need to reverse sort , Then you can put reverse Is set to True
sort It's a list method , It can only be used to sort lists , It's a modification of the original sequence , No new sequences will be generated . Built in sorted Method can be used for any object that can be iterated ( character string 、 list 、 Tuples 、 Dictionary, etc ), It will produce a new sequence , The old objects still exist . If you don't need the old list sequence , Then we can use sort Method .
# list Of sort() Method to sort the list
seq = [1, 3, 5, 4, 2, 6]
print(" The original sequence : ", seq)
seq.sort()
print("sort The sorted sequence : ", seq)
# built-in sorted() Method to sort the list
seq = [1, 3, 5, 4, 2, 6]
s = sorted(seq)
print(" The original sequence : ", seq)
print("sort The sorted sequence : ", seq)
print("sort The new sequence after sorting : ", s)
# built-in sorted() Method to sort strings
seq = "135426"
s = sorted(seq)
print(" The original sequence : ", seq)
print("sort The sorted sequence : ", seq)
print("sort The new sequence after sorting : ", s)
1234567891011121314151617
The results are shown in the following figure :

6. What are the common methods in the list ?
Here are Python Common methods in the list :

7. What is list generation ?
Used to create lists (list) The expression for is a list generator , Also known as list derivation , It is equivalent to for The short form of a loop . A generated list is a list , It provides a simple way to create a list from a sequence . Usually an application applies some operations to each element of a sequence , Use the result as an element to generate a new list , Or create subsequences according to certain criteria .
Every list generator is in for Followed by an expression , Then there are zero to many for or if Clause . The return result is based on the expression from the following for and if The list generated in the context . If you want the expression to derive a tuple , Then you have to use brackets . List Generative Syntax :[ expression for loop ]
# according to range Generate a list of the squares of numbers
num_list = []
for x in range(1, 11):
num_list.append(x * x)
print(num_list)
# If you use list generation , So here's the code :
num_list2 = [x * x for x in range(1, 11)]
print(num_list2)
# Square even numbers
num_list3 = [x * x for x in range(1, 11) if x % 2 == 0]
print(num_list3)
1234567891011
8. String formatting % and .format,f What's the difference between formatting strings ?
There are two ways to format strings :% and format, What's the difference between the two methods ? Here's how it works .

The above code will throw the following at runtime TypeError.
TypeError: not all arguments converted during string formatting
1
Requirements like this need to be written in the following format :
# Define a coordinate value
c = (250, 250)
# Use % format
s1 = " coordinate : %s" % (c,)
# Use format There won't be the above problem
s2 = " coordinate : {}".format(c)
print(s2) # coordinate : (250, 250)
1234567
In general , Use % Enough to meet the needs of the program , But code like this needs to add elements or list types in one place , Best choice format Method . stay format In the method ,{} Represents a placeholder , As shown below :
# {} Represents a placeholder
print("{}, Love tigers ".format("zhangsan")) # zhangsan, Love tigers
print("{},{} Love tigers ".format(" Wang lei ", " Li Mei ")) # Wang lei , Li Mei AI
# 0 Represents the position of the first parameter
print("{1},{0} Love tigers ".format(" Li Mei ", " Wang lei ")) # Wang lei , Li Mei AI
12345
Python 3.6 This new format string appears in version 1 ,f-string Formatted string , Performance is better than the first two ways . The sample code is as follows :
name = "testerzhang"
print(f'Hello {name}.')
print(f'Hello {name.upper()}.')
d = {'id': 1, 'name': 'testerzhang'}
print(f'User[{d["id"]}]: {d["name"]}')
12345
9. Single quotation marks 、 What are the differences between double quotation marks and triple quotation marks ?
Single and double quotation marks are equivalent , If you want a new line , So you need to use symbols (\). Three quotation marks can wrap lines directly , And can include comments , for example :
# A string enclosed in single quotation marks : 'hello'
# A string in double quotation marks : "hello"
# A string in three quotation marks : '''hello'''( Three single quotes ), """hello"""( Three double quotes )
123
It should be noted that :
- A string enclosed in three quotation marks can be wrapped directly .
- You can't put a single quotation mark in a single quotation mark , But you can add \ Or double quotation marks for escape output .
- You can't put double quotation marks in double quotation marks , But you can add \ Or single quotation marks for escape output .
If it means "Let's go" This string , that :

10. Python What are the common string methods in ?
Python The commonly used string built-in functions are as follows :


11. How to judge whether a string is all numbers ?
There are several ways to judge :
(1) Python isdigit() Method to detect whether the string consists of only numbers .

(2) Python isnumeric() Method to detect whether the string consists of only numbers . This method is only for Unicode character string . If you want to define a string as Unicode, So just add... Before the string u The prefix is enough .

(3) Custom function is_number To judge .
# -*- coding: UTF-8 -*-
"""
@author:AmoXiang
@file:3. Determine whether a string is all numbers .py
@time:2020/11/10
"""
def is_number(s):
try:
float(s) # If it works float(s) sentence , return True( character string s Is a floating point number 、 Integers )
return True
except ValueError:
pass
try:
import unicodedata # Handle ASCii The bag of code
unicodedata.numeric(s) # A function that converts a string representing a number to a floating-point number
return True
except (TypeError, ValueError):
pass
return False
# Test strings and numbers
print(is_number("foo")) # False
print(is_number("1")) # True
print(is_number("1.3")) # True
print(is_number("-1.37")) # True
print(is_number("1e3")) # True
12345678910111213141516171819202122232425262728293031
12. Python What built-in functions do dictionaries have ?
Python The dictionary contains the following built-in functions :

Examples of use are as follows :

If you like to program, you can add some Q Group 867067945, You can get free learning materials when you join the group ! The group is full of friends who want to learn programming
13. Dictionary items() Methods and iteritems() How is the method different ?
The dictionary is Python The only mapping type in a language . The hash key in the mapping type object ( key ,key) And the object it points to ( value ,value) It's many-to-one , It is usually considered a variable hash table . The dictionary object is variable , It's a container type , Capable of storing any number of Python object , Other container types can also be included .
Dictionary is a variable container model , And can store any type of object . Each key value of the dictionary (key=>value) Yes, with a colon ( Division , Use commas... Between each pair (,) Division , The whole dictionary is enclosed in curly brackets ({}) in , The format is as follows :
d= {key1:value1, key2:value2}
1
The key must be unique , But the value doesn't have to be unique . The value can take any data type , But the bond has to be immutable , Like strings 、 A number or tuple .
Dictionary items Method can return all dictionary items as a list , Because the dictionary is out of order , So use items Method returns all entries in the dictionary , It's also out of order .
stay Python 2.x in ,items It takes out all the values at once , And return it as a list .iteritems Methods and items The effect of method comparison is roughly the same , It's just that its return value is not a list , It's an iterator , Iterate to get the values inside , Usually when there is a large amount of data ,iteritems than items More efficient .
It should be noted that , stay Python 2.x in ,iteritems() Iterator used to return a list of its own dictionaries (Returns an iterator on allitems(key/value pairs)), It doesn't take up extra memory . however , stay Python 3.x in ,iteritems() The method has been abolished , use items() Replace iteritems(), It can be used for for To loop through . stay Python 3.x Example in :

stay Python 2.x Run the following code :

14. What are the common built-in methods for collections ?
The common built-in methods for collections are shown in the following table :

15. The real question
- Two list object aList = [“a”,“b”,“c”,“d”,“e”,“f”],blist = [“x”,“y”,“z”,“d”,“e”,“f”], Please combine the two in a concise way list, also list The elements in it can't be repeated , The final result needs to be sorted .
- Please send two lists [1,5,7,9] and [2,2,6,8] Merge into [1,2,2,5,6,7,8,9]
- How to output a string in reverse order ?
- Given list object al=[{“name”:“a”,“age”:20},{“name”:“b”,“age”:30},{“name”:“c”,“age”:25}], Please press al Of the elements of age Sort from big to small .
- List = [-2,1,3,-6] , How to achieve absolute value size from small to big List Sort the content in
- Given the dictionary dic = {“a”:3,“bc”:5,“c”:3,“asd”:4,“33”:56,“d”:0}, Sort them in ascending and descending order respectively .
- Given a nested list list2=[[1,2],[4,6],[3,1]], Please follow the... Of the sublist in the nested list respectively 1 And the first 2 Sort elements in ascending order
- Use lambda Function pair list Sort foo=[-5,8,0,4,9,-4,-20,-2,8,2,-4], The output is [0,2,4,8,8,9,-2,-4,-4,-5,-20], Positive numbers go from small to large , Negative numbers go from big to small
- Existing dictionaries d= {“a”:24,“g”:52,“i”:12,“k”:33}, Please press... In the dictionary value Value to sort .
- Existing list foo = [[“zs”,19],[“ll”,54],[“wa”,23],[“df”,23],[“xf”,23]], List nesting, list sorting , If you are the same age , So sort it in alphabetical order .
If you like to program, you can add some Q Group 867067945, You can get free learning materials when you join the group ! The group is full of friends who want to learn programming