Recently, in order to improve python level , Found... On the Internet python exercises , Then according to their own for python Mastery , Sorted out the answers , If the partners have a better way to achieve , You can leave a message below for discussion ~
A known string is “hello_world_yoyo”, How to get a queue [“hello”,”world”,”yoyo”]
test = ‘hello_world_yoyo’
print(test.split(“_”))
result :
[‘hello’, ‘world’, ‘yoyo’]
Process finished with exit code 0
There's a list [“hello”, “world”, “yoyo”] How to concatenate the characters in the list , Get a string “hello_world_yoyo”
test = [“hello”, “world”, “yoyo”]
print(“_”.join(test))
result :
hello_world_yoyo
Process finished with exit code 0
If you don't rely on python Provided join Method , We can also go through for loop , Then concatenate the strings , But in use "+" When connecting strings , The result is a new object ,
use join The result is just to splice the elements in the original list , therefore join High efficiency
test = ["hello", "world", "yoyo"]
# Define an empty string
j = ''
# adopt for loop Print out the data in the list
for i in test:
j = j + "_" + i
# Because through the string splicing above , The data is “_hello_world_yoyo”, There will be an underline in front , So let's remove the underline
print(j.lstrip("_"))
Put the string s Replace each space in with ”%20”
Input :s = “We are happy.”
Output :”We%20are%20happy.”
s = ‘We are happy.’
print(s.replace(’ ', ‘%20’))
result :
We%20are%20happy.
Process finished with exit code 0
Print 99 Multiplication table
for i in range(1, 10):
for j in range(1, i+1):
print(‘{}x{}={} ‘.format(j, i, i*j), end=’’)
print()
result :
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
Process finished with exit code 0
Here's how to use while Cycle to achieve
i = 1
while i <= 9:
j = 1
while j <= i:
print("%d*%d=%-2d"%(i,j,i*j),end = ' ') # %d: Placeholder for integers ,'-2' For left alignment , Two placeholders
j += 1
print()
i += 1
Find the words “welcome” stay character string ”Hello, welcome to my world.” Where in , No return found -1
From the subscript 0 Start index
def test():
message = ‘Hello, welcome to my world.’
world = ‘welcome’
if world in message:
return message.find(world)
else:
return -1
print(test())
result :
7
Process finished with exit code 0
Statistics string “Hello, welcome to my world.” Middle letter w Number of occurrences
Count the words my Number of occurrences
def test():
message = ‘Hello, welcome to my world.’
# Count
num = 0
# for loop message
for i in message:
# Determine if the ‘w’ The string is in message in , be num +1
if ‘w’ in i:
num += 1
return num
print(test())
subject : Enter a string str, Output No m One has only appeared n The second character , As in string gbgkkdehh in ,
Find out the 2 One only appears 1 The second character , Output results :d
def test(str_test, num, counts):
“”"
:param str_test: character string
:param num: Number of string occurrences
:param count: The number of times the string appears
:return:
“”"
# Define an empty array , Store logically processed data
list = []
# for Loop string data
for i in str_test:
# Use count function , Count the number of occurrences of all strings
count = str_test.count(i, 0, len(str_test))
# Judge the number of times the string appears and the set value counts The same number of times , Then store the data in list Array
if count == num:
list.append(i)
# Back to page n The second occurrence of the string
return list[counts-1]
print(test(‘gbgkkdehh’, 1, 2))
result :
d
Process finished with exit code 0
Judgment string a=”welcome to my world” Whether to include the word b=”world”
Include return True, Does not include return False
def test():
message = ‘welcome to my world’
world = ‘world’
if world in message:
return True
return False
print(test())
result :
True
Process finished with exit code 0
Output the specified string A In string B The first place in , If B Contains no A, The output -1
from 0 Start counting
A = “hello”
B = “hi how are you hello world, hello yoyo !”
def test():
message = ‘hi how are you hello world, hello yoyo !’
world = ‘hello’
return message.find(world)
print(test())
result :
15
Process finished with exit code 0
Output the specified string A In string B The last position in , If B Contains no A, Out -1 from 0 Start counting
A = “hello”
B = “hi how are you hello world, hello yoyo !”
def test(string, str):
# Definition last_position The initial value is -1
last_position = -1
while True:
position = string.find(str, last_position+1)
if position == -1:
return last_position
last_position = position
print(test(‘hi how are you hello world, hello yoyo !’, ‘hello’))
result :
28
Process finished with exit code 0
Give a number a, Determine whether a number is odd or even
a1 = 13
a2 = 10
while True:
try:
# Determine whether the input is an integer
num = int(input(‘ Enter an integer :’))
# It's not just numbers that need to be retyped
except ValueError:
print(“ Input is not an integer !”)
continue
if num % 2 == 0:
print(‘ even numbers ’)
else:
print(‘ Odd number ’)
break
result :
Enter an integer :100
even numbers
Process finished with exit code 0
Enter a name , Judge whether the surname is Wang
a = “ Wang Wu ”
b = “ Lao Wang ”
def test():
user_input = input(“ Please enter your name :”)
if user_input[0] == ' king ':
return " User surname: Wang "
return " The user is not surnamed Wang "
print(test())
result :
Please enter your name : Wang Zong
User surname: Wang
Process finished with exit code 0
How to judge whether a string is composed of pure numbers
a = “123456”
b = “yoyo123”
This answer , In fact, there are some tricks , utilize python The type provided is converted to , Converts user entered data to a floating point number type , If the conversion throws an exception , Then judge that the number is not composed of pure numbers
def test(num):
try:
return float(num)
except ValueError:
return " Please enter a number "
print(test('133w3'))
The string a = “This is string example….wow!” All in capitals
character string b = “Welcome To My World” All lowercase
a = ‘This is string example….wow!’
b = ‘Welcome To My World’
print(a.upper())
print(b.lower())
The string a = “ welcome to my world “ Remove the leading and trailing spaces
python Provides strip() Method , You can remove the leading and trailing spaces
rstrip() Remove trailing spaces
lstrip() Remove the first space
replace(" ", “”) Remove all spaces
a = ' welcome to my world '
print(a.strip())
It can also be implemented recursively
def trim(s):
flag = 0
if s[:1]==' ':
s = s[1:]
flag = 1
if s[-1:] == ' ':
s = s[:-1]
flag = 1
if flag==1:
return trim(s)
else:
return s
print(trim(' Hello world! '))
adopt while Cycle to achieve
def trim(s):
while(True):
flag = 0
if s[:1]==' ':
s = s[1:]
flag = 1
if s[-1:] == ' ':
s = s[:-1]
flag = 1
if flag==0:
break
return s
print(trim(' Hello world! '))
s = “ajldjlajfdljfddd”, De duplication and sort output from small to large ”adfjl”
def test():
s = ‘ajldjlajfdljfddd’
# Define an array to store data
str_list = []
# for loop s Data in string , Then add the data to the array
for i in s:
# Judge if the string already exists in the array , Remove the string , Add a new string
if i in str_list:
str_list.remove(i)
str_list.append(i)
# Use sorted Method , Sort the letters
a = sorted(str_list)
# sorted Method returns a list , Here, convert the list data into a string
return "".join(a)
print(test())
result :
adfjl
Process finished with exit code 0
subject Print out the following pattern ( The diamond ):
def test():
n = 8
for i in range(-int(n/2), int(n/2) + 1):
print(" "*abs(i), "*"*abs(n-abs(i)*2))
print(test())
result :
**
****
******
********
******
****
**
Process finished with exit code 0
subject Give one not more than 5 Bit positive integer , requirement :
One 、 Find out how many digits it is ,
Two 、 Print out the numbers in reverse order .
a = 12345
class Test:
# Calculate the number of digits
def test_num(self, num):
try:
# Define a length The variable of , To calculate the length of the number
length = 0
while num != 0:
# Judge when num Not for 0 When , Then divide each time by 10 integer
length += 1
num = int(num) // 10
if length > 5:
return " Please enter the correct number "
return length
except ValueError:
return " Please enter the correct number "
# Print out single digits in reverse order
def test_sorted(self, num):
if self.test_num(num) != " Please enter the correct number ":
# Print out numbers in reverse order
sorted_num = num[::-1]
# Returns the number of digits in reverse order
return sorted_num[-1]
print(Test().test_sorted(‘12346’))
result :
1
Process finished with exit code 0
If one 3 The number of digits is equal to the cubic sum of its digits , Call this number narcissus number .
for example :153 = 1^3 + 5^3 + 3^3, therefore 153 It's a narcissus number
So here comes the question , seek 1000 Number of daffodils in (3 digit )
def test():
for num in range(100, 1000):
i = num // 100
j = num // 10 % 10
k = num % 10
if i ** 3 + j ** 3 + k ** 3 == num:
print(str(num) + " It's Narcissus ")
test()
seek 1+2+3…+100 and
i = 1
for j in range(101):
i = j + i
print(i)
result :
5051
Process finished with exit code 0
Calculation 1-2+3-4+5-…-100 Value
def test(sum_to):
# Define an initial value
sum_all = 0
# Loop the data you want to calculate
for i in range(1, sum_to + 1):
sum_all += i * (-1) ** (1 + i)
return sum_all
if name == ‘main’:
result = test(sum_to=100)
print(result)
-50
Process finished with exit code 0
Calculation formula 13 + 23 + 33 + 43 + …….+ n3
Fulfill the requirements :
Input : n = 5
Output : 225
Corresponding formula : 13 + 23 + 33 + 43 + 53 = 225
def test(n):
sum = 0
for i in range(1, n+1):
sum += i*i*i
return sum
print(test(5))
result :
225
Process finished with exit code 0
It is known that a The value of is ”hello”,b The value of is ”world”, How to exchange a and b Value ?
obtain a The value of is ”world”,b The value of is ”hello”
a = ‘hello’
b = ‘world’
c = a
a = b
b = c
print(a, b)
How to judge whether an array is a symmetric array :
requirement : Determine whether the array elements are symmetrical . for example [1,2,0,2,1],[1,2,3,3,2,1] These are all symmetric arrays
use Python Code to determine , Is symmetric array printing True, Not printing False, Such as :
x = [1, “a”, 0, “2”, 0, “a”, 1]
def test():
x = [1, 'a', 0, '2', 0, 'a', 1]
# By subscript , Compare strings in reverse order
if x == x[::-1]:
return True
return False
print(test())
result :
True
Process finished with exit code 0
If there's a list a=[1,3,5,7,11]
problem :1 How to reverse it to [11,7,5,3,1]
2. Take the number with odd digit value , Such as [1,5,11]
def test():
a = [1, 3, 5, 7, 11]
# Print the data in the array in reverse order
print(a[::-1])
# Define a variable for counting
count = 0
for i in a:
# Judge one data in each cycle list , The counter will +1
count += 1
# If the counter is odd , Then print it out
if count % 2 != 0:
print(i)
test()
result :
[11, 7, 5, 3, 1]
1
5
11
Process finished with exit code 0
problem : On the list a The numbers in are sorted from small to large
a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8]
a = [1, 6, 8, 11, 9, 1, 8, 6, 8, 7, 8]
print(sorted(a))
result :
[1, 1, 6, 6, 7, 8, 8, 8, 8, 9, 11]
Process finished with exit code 0
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
Find the maximum and minimum values in the list
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
print(max(L1))
print(min(L1))
result :
88
1
Process finished with exit code 0
It's through python Self contained function , Here is a calculation program you can write yourself , Post code :
class Test(object):
def __init__(self):
# Test list data
self.L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
# Take the first value from the list , For data size comparison
self.num = self.L1[0]
def test_small_num(self, count):
"""
:param count: count by 1, Then it means to calculate the maximum value , by 2 when , Represents the minimum value
:return:
"""
# for Loop through the data in the list
for i in self.L1:
if count == 1:
# Loop judgment when the data in the array is smaller than the initial value , Replace the initial value with
if i > self.num:
self.num = i
elif count == 2:
if i < self.num:
self.num = i
elif count != 1 or count != 2:
return " Please input the correct data "
return self.num
print(Test().test_small_num(1))
print(Test().test_small_num(2))
result :
88
1
Process finished with exit code 0
a = [“hello”, “world”, “yoyo”, “congratulations”]
Find the longest word in the list
def test():
a = [“hello”, “world”, “yoyo”, “congratulations”]
# Count the length of the first value in the array
length = len(a[0])
for i in a:
# Loop through the data in the array , When the data in the array is larger than the initial value length The shift supervisor in , Then replace length The default value of
if len(i) > length:
length = i
return length
print(test())
result :
congratulations
Process finished with exit code 0
Take out the three largest values in the list
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
def test():
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
return sorted(L1)[:3]
print(test())
result :
[1, 2, 2]
Process finished with exit code 0
a = [1, -6, 2, -5, 9, 4, 20, -3] Sort by the absolute value of the number in the list from small to large
def test():
a = [1, -6, 2, -5, 9, 4, 20, -3]
# Define an array , Store the processed absolute value data
lists = []
for i in a:
# Use abs() Method handles absolute values
lists.append(abs(i))
return lists
print(test())
result :
[1, 6, 2, 5, 9, 4, 20, 3]
Process finished with exit code 0
b = [“hello”, “helloworld”, “he”, “hao”, “good”]
Press list Word length flashback inside
def test():
b = ["hello", "helloworld", "he", "hao", "good"]
count = {}
# Loop through the array to summarize the length of each string
for i in b:
# Call data statistics dictionary format , String as key , String length as value
count[i] = len(i)
# According to the dictionary value , Sort dictionary data from large to small
message = sorted(count.items(), key=lambda x:x[1], reverse=True)
lists = []
for j in message:
# Loop the processed data , Add to a new array
lists.append(j[0])
print(lists)
test()
result :
[‘helloworld’, ‘hello’, ‘good’, ‘hao’, ‘he’]
Process finished with exit code 0
L1 = [1, 2, 3, 11, 2, 5, 3, 2, 5, 33, 88]
How to use one line of code to get [1, 2, 3, 5, 11, 33, 88]
print(sorted(set(L1)))
result :
[1, 2, 3, 5, 11, 33, 88]
Process finished with exit code 0
Remove duplicate values from the list ( Keep only the first ), It is required to keep the original list order
Such as a=[3, 2, 1, 4, 2, 6, 1] Output [3, 2, 1, 4, 6]
a = [3, 2, 1, 4, 2, 6, 1]
lists = []
for i in a:
if i not in lists:
lists.append(i)
print(lists)
result :
[3, 2, 1, 4, 6]
Process finished with exit code 0
a = [1, 3, 5, 7]
b = [‘a’, ‘b’, ‘c’, ‘d’]
How to get [1, 3, 5, 7, ‘a’, ‘b’, ‘c’, ‘d’]
a = [1, 3, 5, 7]
b = [‘a’, ‘b’, ‘c’, ‘d’]
for i in b:
a.append(i)
print(a)
result :
[1, 3, 5, 7, ‘a’, ‘b’, ‘c’, ‘d’]
Process finished with exit code 0
Generate a single line of code that contains 1-10 A list of all even numbers between
print([i for i in range(2, 11, 2) if i % 2 == 0])
result :
[2, 4, 6, 8, 10]
Process finished with exit code 0
list a = [1,2,3,4,5], Calculate the square of the list members , obtain [1,4,9,16,25]
a = [1, 2, 3, 4, 5]
lists = []
for i in a:
lists.append(i*i)
print(lists)
result :
[1, 4, 9, 16, 25]
Process finished with exit code 0
Use list derivation , Put... In the list a = [1, 3, -3, 4, -2, 8, -7, 6]
Find out more than 0 Number of numbers , Regenerate a new list
a = [1, 3, -3, 4, -2, 8, -7, 6]
print([i for i in a if i > 0])
result :
[1, 3, 4, 8, 6]
Process finished with exit code 0
Count the numbers in a queue , How many positive numbers are there , How many negative numbers , Such as [1, 3, 5, 7, 0, -1, -9, -4, -5, 8]
def test():
lists = [1, 3, 5, 7, 0, -1, -9, -4, -5, 8]
# Define a variable , Calculate positive number
positive_num = 0
# Calculate negative numbers
negative_num = 0
for i in lists:
# Judge that the data in the circular array is greater than 0, Then a positive number will +1
if i > 0:
negative_num += 1
# because 0 It's neither positive nor negative , So we judge that it is less than 0 It's a negative number
elif i < 0:
positive_num += 1
return positive_num, negative_num
print(test())
result :
(4, 5)
Process finished with exit code 0
a = [“ Zhang San ”,” Zhang Si ”,” Zhang Wu ”,” The king 2 ”] How to delete the surname Zhang
def test():
a = [“ Zhang San ”, “ Zhang Si ”, “ Zhang Wu ”, “ The king 2 ”]
for i in a[:]:
if i[0] == ' Zhang ':
a.remove(i)
return a
print(test())
result :
[‘ The king 2 ’]
Process finished with exit code 0
When implementing this requirement , Step into a hole , When I was for When the first name in the array is equal to Zhang , The code judgment at that time was written like this
for i in a:
if i[0] == ' Zhang ':
Then the printed data is [‘ Zhang Si ’, ‘ The king 2 ’], At that time, I still had doubts , My logical judgment is right , Why? ‘ Zhang Si ’ The name will be printed out , So I hit a breakpoint to check .
Find out when the first ‘ Zhang San ’ After being deleted , When you cycle again , Just skip it ‘ Zhang San ’, Baidu found out after checking , Pictured :
Interested partners , Check out this article :https://www.cnblogs.com/zhouziyuan/p/10137086.html
There's a list a = [1, 3, 5, 7, 0, -1, -9, -4, -5, 8] Use filter Function to filter out a value greater than 0 Number of numbers
a = [1, 3, 5, 7, 0, -1, -9, -4, -5, 8]
def test(a):
return a < 0
temlists = filter(test, a)
print(list(temlists))
result :
[-1, -9, -4, -5]
Process finished with exit code 0
list b = [“ Zhang San ”, “ Zhang Si ”, “ Zhang Wu ”, “ The king 2 ”] Filter out the name of Zhang
b = [“ Zhang San ”, “ Zhang Si ”, “ Zhang Wu ”, “ The king 2 ”]
def test(b):
return b[0] != ‘ Zhang ’
print(list(filter(test, b)))
result :
[‘ The king 2 ’]
Process finished with exit code 0
Filter out the students who failed in the list
a = [
{“name”: “ Zhang San ”, “score”: 66},
{“name”: “ Li Si ”, “score”: 88},
{“name”: “ Wang Wu ”, “score”: 90},
{“name”: “ Chen Liu ”, “score”: 56},
]
a = [
{“name”: “ Zhang San ”, “score”: 66},
{“name”: “ Li Si ”, “score”: 88},
{“name”: “ Wang Wu ”, “score”: 90},
{“name”: “ Chen Liu ”, “score”: 56}
]
print(list(filter(lambda x: x.get(“score”) >= 60, a)))
return :
[{‘name’: ‘ Zhang San ’, ‘score’: 66}, {‘name’: ‘ Li Si ’, ‘score’: 88}, {‘name’: ‘ Wang Wu ’, ‘score’: 90}]
Yes A list a = [1, 2, 3, 11, 2, 5, 88, 3, 2, 5, 33]
Find the largest number in the list , Position of appearance , Subscript from 0 Start
def test():
a = [1, 2, 3, 11, 2, 5, 88, 3, 2, 5, 33]
# Find the largest number in the array
b = max(a)
count = 0
# Define a counter , Each time you loop a number , Then the counter +1, Subscript used to record numbers
for i in a:
count += 1
# Judge when the loop reaches the maximum number , The exit
if i == b:
break
return count -1
print(test())
result :
6
Process finished with exit code 0
**a = [
‘my’, ‘skills’, ‘are’, ‘poor’, ‘I’, ‘am’, ‘poor’, ‘I’,
‘need’, ‘skills’, ‘more’, ‘my’, ‘ability’, ‘are’,
‘so’, ‘poor’
]
Find the most frequent elements in the list
def test():
a = [
“my”, “skills”, “are”, “poor”, “I”, “am”, “poor”, “I”,
“need”, “skills”, “more”, “my”, “ability”, “are”,
“so”, “poor”
]
dicts = {}
for i in a:
# Count the number of occurrences of each string in the array , Store data in a dictionary
if i not in dicts.keys():
dicts[i] = a.count(i)
return sorted(dicts.items(), key=lambda x: x[1], reverse=True)[0][0]
print(test())
result :
poor
Process finished with exit code 0
Given an array of integers A And its size n, At the same time, given the element to find val,
Please return its position in the array ( from 0 Start ), If the element does not exist , return -1.
If the element appears more than once, please return to the first found location
Such as A1=[1, “aa”, 2, “bb”, “val”, 33]
or A2 = [1, “aa”, 2, “bb”]
def test(lists, string):
“”"
:param lists: Array
:param string: String to find
:return:
“”"
if string not in lists:
return -1
count = 0
for i in lists:
count += 1
if i == string:
return count - 1
print(test([1, “aa”, “val”, 2, “bb”, “val”, 33], ‘val’))
result :
2
Process finished with exit code 0
Given an array of integers nums And a target value target , Please find the two integers with and as the target value in the array , And return to him
Our array subscript .
You can assume that each input corresponds to only one answer . however , The same element in an array cannot be used twice .
Example :
Given nums=[2,7,11,15],target=9
because nums[0] + nums[1] =2+7 = 9
So back [0, 1]
def test(target=9):
num = [2, 7, 11, 15]
# Count the length of the array
length = len(num)
dicts = {}
for i in range(length):
# Add two for loop , The second time for loop , The position of the loop will be one more time than the first loop
for j in range(i + 1, length):
# Put the data after the cycle in the list , Use a dictionary key Unique attributes handle data
dicts.update({num[i] + num[j]: {i, j}})
# Printed data , Is the format of the element , According to the title , Convert data into a dictionary
lists = []
for nums in dicts[target]:
lists.append(nums)
return lists
print(test())
result :
[0, 1]
Process finished with exit code 0
a = [[1,2],[3,4],[5,6]] How one sentence of code gets [1, 2, 3, 4, 5, 6]
a = [[1, 2], [3, 4], [5, 6]]
lists = []
for i in a:
# secondary for loop , Store data in lists in
for j in i:
lists.append(j)
print(lists)
result :
[1, 2, 3, 4, 5, 6]
Process finished with exit code 0
Two dimensional array value ( matrix ), Yes a = [[“A”, 1], [“B”, 2]] , How to take out 2
import numpy
a = [[“A”, 1], [“B”, 2]]
x = numpy.array(a)
print(x[1, 1])
result :
2
Process finished with exit code 0
List to string ,L = [1, 2, 3, 5, 6], How to get ‘12356’?
L = [1, 2, 3, 5, 6]
lists = [str(i) for i in L]
print(‘’.join(lists))
result :
12356
Process finished with exit code 0
a = [“a”, “b”, “c”]
b = [1, 2, 3]
How to get {‘a’: 1, ‘b’: 2, ‘c’: 3}
a = [“a”, “b”, “c”]
b = [1, 2, 3]
c = {k: v for k, v in zip(a, b)}
print
result :
{‘a’: 1, ‘b’: 2, ‘c’: 3}
The following list
people = [
{“name”:”yoyo”, “age”: 20},
{“name”:”admin”, “age”: 28},
{“name”:”zhangsan”, “age”: 25},
]
in years age Sort from small to large
people = [
{“name”: “yoyo”, “age”: 20},
{“name”: “admin”, “age”: 28},
{“name”: “zhangsan”, “age”: 25},
]
print(sorted(people, key=lambda x: x[‘age’], reverse=True))
result :
[{‘name’: ‘admin’, ‘age’: 28}, {‘name’: ‘zhangsan’, ‘age’: 25}, {‘name’: ‘yoyo’, ‘age’: 20}]
Process finished with exit code 0
existing nums=[2, 5, 7] , How to insert a number at the end of the data 9 , How to be in 2 Insert the number after 0
nums=[2, 5, 7]
nums.append(9)
nums.insert(1, 0)
print(nums)
result :
[2, 0, 5, 7, 9]
Process finished with exit code 0
There's a list a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
How to clutter the list a The order of , Get an unordered list each time
import random
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(a)
print(a)
result :
[2, 7, 9, 4, 8, 1, 3, 5, 6]
Process finished with exit code 0
Output 1-100 except 3 more than 1 Number of numbers , The result is tuple
tuples = ()
for i in range(1, 101):
# Judge divided by 3 more than 1 Number of numbers
if i % 3 == 1:
# Add data to Yuanzu
tuples += (i, )
print(tuples)
take (‘a’, ‘b’, ‘c’, ‘d’, ‘e’) and (1,2, 3, 4, 5) Two tuple Turn into
(1, 2, 3, 4, 5) by key, (‘a’, ‘b’, ‘c’, ‘d’, ‘e’) by value Dictionary
def test():
a = (1, 2, 3, 4, 5)
b = (“a”, “b”, “c”, “d”, “e”)
# Use zip Function to combine elements into multiple primitives
c = list(zip(a, b))
dicts = {}
# Convert data to dictionary type
for i in c:
dicts[i[0]] = i[1]
return dicts
print(test())
result :
{1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’, 5: ‘e’}
Process finished with exit code 0
Convert values in the dictionary that are numeric to strings , Such as a = {‘aa’: 11, ‘bb’: 222}
obtain {‘aa’: ‘11’, ‘bb’: ‘222’}
def test():
a = {‘a’: 11, ‘bb’: 222}
for i in a.items():
a.update({i[0]: str(i[1])})
return a
result :
{‘a’: ‘11’, ‘bb’: ‘222’}
Process finished with exit code 0
a = [1,2,3] and b = [(1),(2),(3) ] as well as c = [(1,),(2,),(3,) ] The difference between ?
a = [1,2,3] Normal list
b = [(1),(2),(3)] Although each element of the list is bracketed , But when there is only one element in the parentheses and there is no comma , Its data type is the data type of the element itself
b = [(1,),(2,),(3,)] The element types in the list are tuple types
map function , There's a list a = [1, 2, 3, 4] Calculate each number in the list divided by 2 Take out the remainder obtain [1,0,1,0]
ef test():
a = [1, 2, 3, 4]
lists = []
for i in a:
lists.append(i % 2)
return lists
print(test())
result :
[1, 0, 1, 0]
Process finished with exit code 0
map The function will list [1,2,3,4,5] Use python Method into [1,4,9,16,25]
def test():
a = [1, 2, 3, 4, 5]
new_list = []
for i in a:
new_list.append(i*i)
return new_list
print(test())
result :
[1, 4, 9, 16, 25]
Process finished with exit code 0
map Function to list a=[1,3,5],b=[2,4,6] Multiply to get [2,12,30]
a = [1, 3, 5]
b = [2, 4, 6]
print(list(map(lambda x, y: x*y, a, b)))
result :
[2, 12, 30]
Process finished with exit code 0
reduce Function calculation 1-100 And
from functools import reduce
def test():
lists = []
# for Loop to add... To the list 1-100 The data of
for i in range(1, 101):
lists.append(i)
# Realize data addition
return reduce(lambda x, y: x + y, lists)
print(test())
result :
5050
Process finished with exit code 0
Two dictionaries merge a={“A”:1,”B”:2},b={“C”:3,”D”:4}
a = {“A”: 1, “B”: 2}
b = {“C”: 3, “D”: 4}
b.update(a)
print(b)
result :
{‘C’: 3, ‘D’: 4, ‘A’: 1, ‘B’: 2}
Process finished with exit code 0
m1={‘a’:1,’b’:2,’c’:1} # Will be the same value Of key Assemble in list in , Output {1:[‘a’,’c’],2:[‘b’]}
def test():
m1={“a”: 1, “b”: 2, “c”: 1}
new_dict = {}
# loop m1 Data in the dictionary
for key, value in m1.items():
# Determine if the m1 The value in the dictionary is not in the newly defined new_dist In the dictionary
if value not in new_dict:
# Add key value pairs to the new dictionary
new_dict[value] = [key]
else:
# If the added key already exists , Then add the value directly
new_dict[value].append(key)
return new_dict
print(test())
result :
{1: [‘a’, ‘c’], 2: [‘b’]}
Process finished with exit code 0
d={“name”:”zs”,”age”:18,”city”:” Shenzhen ”,”tel”:”1362626627”}
Dictionaries are sorted by key from small to large
def test():
d = {“name”: “zs”, “age”: 18, “city”: “ Shenzhen ”, “tel”: “1362626627”}
# Sort the data in the dictionary
dict2 = sorted(d.items(), key=lambda d: d[0], reverse=False)
# After sorting, the data type will become a list type , Here the data is converted back into a dictionary
new_dict = {}
for i in dict2:
new_dict[i[0]] = i[1]
return new_dict
print(test())
result :
{‘age’: 18, ‘city’: ‘ Shenzhen ’, ‘name’: ‘zs’, ‘tel’: ‘1362626627’}
Process finished with exit code 0
a = [2, 3, 8, 4, 9, 5, 6]
b = [2, 5, 6, 10, 17, 11]
1. find a and b All of them contain elements of
2.a or b All elements contained in
3.a Contains and sets b Elements not contained in
a = [2, 3, 8, 4, 9, 5, 6]
b = [2, 5, 6, 10, 17, 11]
print(list(set(a).union(set(b))))
print(list(set(a).intersection(set(b))))
print(list(set(a) ^ set(b)))
result :
[3, 4, 8, 9, 10, 11, 17]
[2, 3, 4, 5, 6, 8, 9, 10, 11, 17]
[2, 5, 6]
Process finished with exit code 0
Function calculation 10!
def f(num):
if num == 1 or num == 0:
return 1
else:
# Use recursion to realize
return num * f(num - 1)
print(f((10)))
result :
3628800
Process finished with exit code 0
Yes 1、2、3、4 How many different non repeating three digit numbers can a number form
Print these three digit combinations separately
l = [“1”, “2”, “3”, “4”]
n = len(l)
for i in range(n):
for j in range(n):
for k in range(n):
if i != k and k != j and i != j:
print(l[i] + l[j] + l[k])
Find... In the following text The length of each line exceeds 3 's words :
Call me Ishmael. Some years ago - never mind how long precisely - having
little or no money in my purse, and nothing particular to interest me
on shore, I thought I would sail about a little and see the watery part
of the world. It is a way I have of driving off the spleen, and regulating
the circulation. - Moby Dick
python The expected result of ( Try not to exceed 3 All right ):
[[‘Call’, ‘Ishmael.’, ‘Some’, ‘years’, ‘never’, ‘mind’, ‘long’, ‘precisely’, ‘having’],
[‘little’, ‘money’, ‘purse,’, ‘nothing’, ‘particular’, ‘interest’],
[‘shore,’, ‘thought’, ‘would’, ‘sail’, ‘about’, ‘little’, ‘watery’, ‘part’],
[‘world.’, ‘have’, ‘driving’, ‘spleen,’, ‘regulating’],
[‘circulation.’, ‘Moby’, ‘Dick’]]]
a='''Call me Ishmael. Some years ago - never mind how long precisely - having
little or no money in my purse, and nothing particular to interest me
on shore, I thought I would sail about a little and see the watery part
of the world. It is a way I have of driving off the spleen, and regulating
the circulation. - Moby Dick'''
list1=[[j for j in i.split(' ') if len(j)>3 ]for i in a.split('
')]
print(list1)
result :
[['Call', 'Ishmael.', 'Some', 'years', 'never', 'mind', 'long', 'precisely', 'having'], ['little', 'money', 'purse,', 'nothing', 'particular', 'interest'], ['shore,', 'thought', 'would', 'sail', 'about', 'little', 'watery', 'part'], ['world.', 'have', 'driving', 'spleen,', 'regulating'], ['circulation.', 'Moby', 'Dick']]
Process finished with exit code 0
a = [11, 2, 33, 1, 5, 88, 3]
Bubble sort :
Compare two adjacent elements in turn , If the order ( From small to large 、 First letter from A To Z)
Mistakes are exchanged
def bubbleSort(arr):
n = len(arr)
# Traverse all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
arr = [11, 2, 33, 1, 5, 88, 3]
bubbleSort(arr)
print(arr)
result :
[1, 2, 3, 5, 11, 33, 88]
Process finished with exit code 0
There's a data list of dict as follows
a = [
{“yoyo1”: “123456”},
{“yoyo2”: “123456”},
{“yoyo3”: “123456”},
]
Write to a local txt file , The content format is as follows :
yoyo1,123456
yoyo2,123456
yoyo3,123456
def test():
a = [
{“yoyo1”: “123456”},
{“yoyo2”: “123456”},
{“yoyo3”: “123456”},
]
# Open a file named test.txt The file of , If the file doesn't exist , Automatically create
with open('test.txt', 'w') as f:
for i in a:
# Dictionary in circular array
for key, value in i.items():
# Store data txt In file
f.write("{0},{1}
“.format(key, value))
print(”{0},{1}
".format(key, value))
test()