100 simple exercises in Python,

100 simple Python practice questions, covering 9 categories including lists, dictionaries, tuples, sets, strings, formatted output, type and integer conversion, file reading and writing, and miscellaneous items.

see the answer

1. Merge the tuple (1,2,3) and the set {4,5,6} into a list.

2. Add integer elements 7 and 0 at the beginning and end of the list [1,2,3,4,5,6] respectively.

3. Reverse the list [0,1,2,3,4,5,6,7] .

4. Reversing the list [0,1,2,3,4,5,6,7] gives the index number of element 5 in the list.

5. Count the number of elements of True, False, 0, 1, 2 in the list [True, False, 0, 1, 2] respectively. What do you find?

6. Remove the element 'x' from the list [True,1,0,'x',None,'x',False,2,True].

7. Delete the element with index number 4 from the list [True,1,0,'x',None,'x',False,2,True].

8. Delete elements with odd (or even) index numbers in the list.

9. Clear all elements in the list.

10. Sort the list [3,0,8,5,7] in ascending order and descending order respectively.

11. Set the elements greater than 5 in the list [3,0,8,5,7] to 1, and set the rest of the elements to 0.

lst=[3,0,8,5,7]

for k,v in enumerate(lst):

    if v>5:

        lst[k]=1

    else:

        lst[k]=0

12. Traverse the list ['x', 'y', 'z'] and print each element and its corresponding index number.

lst=[3,0,8,5,7]

for k,v in enumerate(lst):

    print(k,v)

13. Split the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] into two lists of odd and even.

lst=[0,1,2,3,4,5,6,7,8,9]

life=lst[::2]

lot=lst[1::2]

14. Sort the two-dimensional list [[6, 5], [3, 7], [2, 8]] according to the size of the first and last elements of each row.

lst=[[6,5],[3,7],[2,8]]

lst.sort()

lst.sort(key=lambda x:x[-1])

15. Starting from the index 3 of the list [1,4,7,2,5,8], insert all elements of the list ['x','y','z'] in sequence.

lst1=[1,4,7,2,5,8]

lst2=['x','y','z']

lst=lst1[:3]+lst2+lst1[3:]

16. Quickly generate a list of integers in the interval [5,50).

lst=list(range(5,50))

17. If a = [1,2,3], set b = a, execute b[0] = 9, a[0] will also be changed. why? How to avoid it?

Change to b=a.copy()

18. Convert the lists ['x','y','z'] and [1,2,3] into [('x',1),('y',2),('z',3 )] form.

lst=list(zip(['x','y','z'],[1,2,3])) #Packed as a list of tuples

19. Return all the keys in the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21} as a list.

    s1={'Alice':20,'Beth':18,'Cecil':21}

    list(s1.keys())

20. Return all the values ​​in the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21} in the form of a list.

    list(s1.values())

21. Return a tuple consisting of all key-value pairs in the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21} in the form of a list.

    list(s1.items())

22. Add the key-value pair 'David': 19 to the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21}, and update the value of Cecil to 17.

    s1['David']=19

s1['Cecil']=17

23. After deleting the Beth key in the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21}, empty the dictionary.

s1.pop('Beth')

s1.clear()

24. Determine whether David and Alice are in the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21}.

s1={'Alice':20,'Beth':18,'Cecil':21}

'David' in s1

'Alice' in s1

25. Traverse the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21} and print key-value pairs.

for k,v in s1.items():

    print(k,v)

26. If a = dict(), let b = a, execute b.update({'x':1}), a is also changed. why? How to avoid it?

    Change to b=a.copy()

27. Use each element in the list ['A','B','C','D','E','F','G','H'] as the key, and the default value is 0 , creating a dictionary.

    s1={x:0 for x in ['A','B','C','D','E','F','G','H']}

28. Convert the two-dimensional structure [['a',1],['b',2]] and (('x',3),('y',4)) into a dictionary.

    d1={k:v for k,v in [['a',1],['b',2]]+list((('x',3),('y',4)))}

29. Merge the tuples (1,2) and (3,4) into one tuple.

lst=tuple((1,2)+(3,4))

30. Unpack the three elements of the space coordinate tuple (1,2,3) corresponding to variables x, y, z.

x,y,z=(1,2,3)

31. Return the index number of the 'Cecil' element in the tuple ('Alice', 'Beth', 'Cecil').

    ('Alice','Beth','Cecil').index('Cecil')

32. Return the number of elements 2 in the tuple (2,5,3,2,4).

    (2,5,3,2,4).count(2)

33. Determine whether 'Cecil' is in the tuple ('Alice', 'Beth', 'Cecil').

    'Cecil' in ('Alice','Beth','Cecil')

34. Return the new tuple after the element 9 is inserted at the index number 2 of the tuple (2,5,3,7).

    lst=list((2,5,3,7))

lst.insert(2,9)

tuple(lst)

35. Create an empty collection and add three elements {'x', 'y', 'z'}.

    s=set()

s.update({'x','y','z'})

36. Delete the 'z' element in the collection {'x', 'y', 'z'}, add j element 'w', and then empty the entire collection.

s={'x','y','z'}

s.remove('z')

s.add('w')

s.clear()

37. Return the elements in the set {'A', 'D', 'B'} that do not appear in the set {'D', 'E', 'C'} (difference set).

    {'A','D','B'}-{'D','E','C'}

38. Return the union of two sets {'A', 'D', 'B'} and {'D', 'E', 'C'}.

    {'A','D','B'}|{'D','E','C'}

39. Return the intersection of two sets {'A','D','B'} and {'D','E','C'}.

    {'A','D','B'}&{'D','E','C'}

40. Return the set of two sets {'A', 'D', 'B'} and {'D', 'E', 'C'} without repeated elements.

    {'A','D','B'}^{'D','E','C'}

41. Determine whether the two sets {'A', 'D', 'B'} and {'D', 'E', 'C'} have duplicate elements.

    {'A','D','B'}&{'D','E','C'}!=set()

42. Determine whether the set {'A', 'C'} is a subset of the set {'D', 'C', 'E', 'A'}.

    {'A','C'} < {'D','C','E','A'}

43. Remove duplicate elements in the array [1,2,5,2,3,4,5,'x',4,'x'].

    lst=list(set([1,2,5,2,3,4,5,'x',4,'x']))

44. Returns all uppercase, all lowercase, and case-swapped forms of the string 'abCdEfg'.

    s='abCdEfg'

s.upper()

s.lower()

s.islower()

45. Determine whether the first letter of the string 'abCdEfg' is capitalized, whether all letters are lowercase, and whether all letters are uppercase.

    s='abCdEfg'

s.istitle() #Judge the capitalization of the first letter

s.isupper()

s.islower()

46. ​​Return the initial capitalization of the string 'this is python' and the initial capitalization of each word in the string.

   

47. Determine whether the string 'this is python' starts with 'this' and ends with 'python'.

48. Return the number of occurrences of 'is' in the string 'this is python'.

49. Return the position of the first and last occurrence of 'is' in the string 'this is python'.

50. Slice the string 'this is python' into 3 words.

51. Return the result of slicing the string 'blog.csdn.net/xufive/article/details/102946961' by the path separator.

52. After slicing the string '2.72, 5, 7, 3.14' with half-width commas, convert each element into a floating point type or an integer.

53. Determine whether the string 'adS12K56' is completely alphanumeric, whether it is all digits, whether it is all letters, and whether it is all ASCII codes.

54. Replace 'is' with 'are' in the string 'there is python'.

55. Clear the left and right sides of the string '\t python \n', and the blank characters on the left and right sides.

56. Print three full English character strings (for example, 'ok', 'hello', 'thank you') on separate lines to achieve left, right and center alignment effects.

57. Print three strings (for example, 'Hello, I'm David', 'OK, ok', 'Nice to meet you') in separate lines to achieve left-aligned, right-aligned and centered effects.

58. Add 0 to the left side of the three strings '15', '127', '65535' to make them the same length.

59. Extract the protocol name in the url string 'https://blog.csdn.net/xufive'.

60. Connect each element in the list ['a', 'b', 'c'] with '|' to form a string.

61. Add a half-width comma between two adjacent letters of the string 'abc' to generate a new string.

62. Input the mobile phone number from the keyboard and output a character string like 'Mobile: 186 6677 7788'.

63. Input the year, month, day, hour, minute, and second from the keyboard, and output a character string in the form of '2019-05-01 12:00:00'.

64. Given two floating point numbers 3.1415926 and 2.7182818, format the output string 'pi = 3.1416, e = 2.7183'.

65. Format and output 0.00774592 and 356800000 as scientific notation strings.

66. Format the decimal integer 240 into octal and hexadecimal strings.

67. Convert the decimal integer 240 into a string of binary, octal, or hexadecimal.

68. Convert the character string '10100' into an integer according to binary, octal, decimal, and hexadecimal.

69. Calculate the sum of binary integer 1010, octal integer 65, decimal integer 52, and hexadecimal integer b4.

70. Convert each element in the list [0,1,2,3.14,'x',None,'',list(),{5}] to Boolean.

71. Return the ASCII coded value of characters 'a' and 'A'.

72. Return the characters whose ASCII encoding values ​​are 57 and 122.

73. Write the two-dimensional list [[0.468,0.975,0.446],[0.718,0.826,0.359]] into a csv format file named csv_data, and try to open it with excel.

74. Read the two-dimensional list from the csv_data.csv file.

75. Append the two-dimensional list [[1.468,1.975,1.446],[1.718,1.826,1.359]] to the csv_data.csv file, and then read all the data.

76. Swap the values ​​of the variables x and y.

77. Determine whether the given parameter x is an integer.

78. Determine whether the given parameter x is a list or a tuple.

79. Determine whether 'https://blog.csdn.net' starts with 'http://' or 'https://'. If so, return 'http' or 'https'; otherwise, return None.

80. Determine whether 'https://blog.csdn.net' ends with '.com' or '.net'. If so, return 'com' or 'net'; otherwise, return None.

81. Set integers or floating point numbers greater than 3 in the list [3,'a',5.2,4,{},9,[]] to 1, and the rest to 0.

82. a, b are two numbers, return the smaller or the largest.

83. Find the most frequent number in the list [8,5,2,4,3,6,5,5,1,4,5] and how many times it occurs.

84. Convert the two-dimensional list [[1], ['a', 'b'], [2.3, 4.5, 6.7]] into a one-dimensional list.

85. Convert equal-length key and value lists into dictionaries.

86. Rewrite the logical expression a > 10 and a < 20 using chained comparison operators.

87. Write a function that prints the characters passed in by the function parameters 30 times at an interval of 0.1 seconds without line breaks to achieve a typewriter-like effect.

88. Sum a list of numbers.

89. Return the maximum and minimum values ​​in a list of numbers.

90. Calculate the 3.5 square of 5 and the cube root of 3.

91. Round off 3.1415926 to 5 decimal places.

92. Determine whether two objects are the same in memory.

93. Returns the properties and methods of a given object.

94. Calculate the value of the string expression '(2+3)*5'.

95. Realize the code function contained in the string 'x={"name":"David", "age":18}'.

96. Use the map function to find the cube root of each element in the list [2,3,4,5].

97. Global variables can be defined through the keyword _____ ________ inside the function.

98. If there is no return statement in the function or the return statement does not carry any return value, then the return value of the function is _______ _______.

99. Using the context management keyword __________ can automatically manage the file object, no matter what the reason is to end the statement block in the keyword, it can ensure that the file is closed correctly.

100. It is known that x = [[1,3,3], [2,3,1]], then the expression

The value of sorted(x, key=lambda item:item[0]+item[2]) is_______

reference answer

1. Merge the tuple (1,2,3) and the set {4,5,6} into a list.

list((1,2,3)) + list({4,5,6})

2. Add integer elements 7 and 0 at the beginning and end of the list [1,2,3,4,5,6] respectively.

lst=[1,2,3,4,5,6]

lst.insert(0, 7)

lst.append(0)

3. Reverse the list [0,1,2,3,4,5,6,7] .

lst=[0,1,2,3,4,5,6,7]

lst=lst[::-1]

4. Reversing the list [0,1,2,3,4,5,6,7] gives the index number of element 5 in the list.

lst=[0,1,2,3,4,5,6,7]

lst[::-1].index(5)

5. Count the number of elements of True, False, 0, 1, 2 in the list [True, False, 0, 1, 2] respectively. What do you find?

from collections import Counter

lst=[True,False,0,1,2]

Counter(lst)

Note: The displayed result is Counter({True: 2, False: 2, 2: 1}), indicating that both True and 1 are considered as True, and both False and 0 are considered as False

6. Remove the element 'x' from the list [True,1,0,'x',None,'x',False,2,True].

lst=[True,1,0,'x',None,'x',False,2,True]

while 'x' in lst:

    lst.remove('x')

7. Delete the element with index number 4 from the list [True,1,0,'x',None,'x',False,2,True].

lst=[True,1,0,'x',None,'x',False,2,True]

lst.remove(lst[4])

8. Delete elements with odd (or even) index numbers in the list.

lst=list(range(20))

lst=lst[ : :2] # Keep elements with even index numbers, delete elements with odd index numbers

lst2=list(range(20))

lst2=lst2[1::2] # Keep elements with odd index numbers, delete elements with even index numbers

9. Clear all elements in the list.

lst.clear()

10. Sort the list [3,0,8,5,7] in ascending order and descending order respectively.

lst=[3,0,8,5,7]

lst.sort()

lst.sort(reverse=True)

11. Set the elements greater than 5 in the list [3,0,8,5,7] to 1, and set the rest of the elements to 0.

method one

lst=[3,0,8,5,7]

lst=[1 if x>5 else 0  for  x  in  lst]

Method Two

lst=[3,0,8,5,7]

for  k, v  in  enumerate(lst):

    if  v>5:

        lst[k]=1

    else:

        lst[k]=0

12. Traverse the list ['x', 'y', 'z'] and print each element and its corresponding index number.

lst=['x','y','z']

for  k,v  in  enumerate(lst):

    print(k, v)

13. Split the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] into two lists of odd and even.

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

leven=lst[::2] # even number

lodd=lst[1::2] # odd number

14. Sort the two-dimensional list [[6, 5], [3, 7], [2, 8]] according to the size of the first and last elements of each row.

lst = [[6, 5], [3, 7], [2, 8]]

lst.sort() # sort by the first element of each small list by default

print(lst)

lst.sort(key= lambda x:x[-1]) # custom sort, sort by the tail element of each small list

print(lst)

15. Starting from index 3 of the list [1,4,7,2,5,8], insert all elements of the list ['x','y','z'] in sequence.

lst=[1,4,7,2,5,8]

lst2=['x','y','z']

lst=lst[:3] + lst2 +lst[3:]

16. Quickly generate a list of integers in the interval [5,50).

lst=list(range(5,50))

17. If a = [1,2,3], set b = a, execute b[0] = 9, a[0] will also be changed. why? How to avoid it?

Change to b=a.copy(), so that lists a and b are separated and will not affect each other.

18. Convert the lists ['x','y','z'] and [1,2,3] into [('x',1),('y',2),('z',3 )] form.

lst=list(zip(['x','y','z'],  [1,2,3]))

19. Return all the keys in the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21} as a list.

by = {'Alice': 20, 'Beth': 18, 'Cecil': 21}

list ( this . keys ())

20. Return all the values ​​in the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21} as a list.

by = {'Alice': 20, 'Beth': 18, 'Cecil': 21}

list(di.values())

21. Return a tuple consisting of all key-value pairs in the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21} in the form of a list.

by = {'Alice': 20, 'Beth': 18, 'Cecil': 21}

list ( the . items ())

22. Add the key-value pair 'David': 19 to the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21}, and update the value of Cecil to 17.

by = {'Alice': 20, 'Beth': 18, 'Cecil': 21}

at['David'] = 19

of['Cecil'] = 17

23. After deleting the Beth key in the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21}, empty the dictionary.

by = {'Alice': 20, 'Beth': 18, 'Cecil': 21}

di.pop('What')

at.clear()

24. Determine whether David and Alice are in the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21}.

by = {'Alice': 20, 'Beth': 18, 'Cecil': 21}

'David' in tu

'Alice' in of

25. Traverse the dictionary {'Alice': 20, 'Beth': 18, 'Cecil': 21} and print the key-value pairs.

by = {'Alice': 20, 'Beth': 18, 'Cecil': 21}

for k,v in the.items():

    print(k,v)

26. If a = dict(), let b = a, execute b.update({'x':1}), a is also changed. why? How to avoid it?

Change to b=a.copy()

27. Use each element in the list ['A','B','C','D','E','F','G','H'] as the key, and the default value is 0 , creating a dictionary.

di={x:0 for x in ['A','B','C','D','E','F','G','H']}

28. Convert the two-dimensional structure [['a',1],['b',2]] and (('x',3),('y',4)) into a dictionary.

di={k:v for k,v in [['a',1],['b',2]] + list((('x',3),('y',4)))}

Transformation result: {'a': 1, 'b': 2, 'x': 3, 'y': 4}

29. Merge the tuples (1,2) and (3,4) into one tuple.

lst = list( (1,2) + (3,4))

30. Unpack the three elements of the spatial coordinate tuple (1,2,3) corresponding to the variables x,y,z.

x,y,z = (1,2,3)

31. Return the index number of the 'Cecil' element in the tuple ('Alice','Beth','Cecil').

('Alice','Beth','Cecil').index('Cecil')

32. Returns the number of elements 2 in the tuple (2,5,3,2,4).

(2,5,3,2,4).count(2)

33. Determine if 'Cecil' is in the tuple ('Alice','Beth','Cecil').

'Cecil' in ('Alice','Beth','Cecil')

34. Return the new tuple after the element 9 is inserted at the index number 2 of the tuple (2,5,3,7).

lst = list((2,5,3,7))

lst.insert(2, 9)

tuple(lst)

35. Create an empty collection and add three elements {'x', 'y', 'z'}.

s=set()

s.update({'x','y','z'})

36. Delete the element 'z' from the set {'x','y','z'}, add the element 'w', and empty the entire set.

s = {'x','y','z'}

s.remove('z')

s.add('w')

s.clear()

37. Return the elements in the set {'A','D','B'} that do not appear in the set {'D','E','C'} (subtraction set).

{'A','D','B'} - {'D','E','C'}

38. Return the union of two sets {'A','D','B'} and {'D','E','C'}.

{'A','D','B'} | {'D','E','C'}

39. Return the intersection of two sets {'A','D','B'} and {'D','E','C'}.

{'A','D','B'} & {'D','E','C'}

40. Return the set of the two sets {'A','D','B'} and {'D','E','C'} without repeated elements.

{'A','D','B'} ^ {'D','E','C'}

41. Determine whether the two sets {'A', 'D', 'B'} and {'D', 'E', 'C'} have duplicate elements.

{'A','D','B'} & {'D','E','C'} !=set()

Note: The operation result is True, there are repeated elements; the result is False, there are no repeated elements

42. Determine whether the set {'A','C'} is a subset of the set {'D','C','E','A'}.

{'A','C'} < {'D','C','E','A'}

43. Remove duplicate elements in the array [1,2,5,2,3,4,5,'x',4,'x'].

lst = list(set([1,2,5,2,3,4,5,'x',4,'x']))

44. Returns all uppercase, all lowercase, and case-swapped versions of the string 'abCdEfg'.

s='abCdEfg'

s.upper()

s.lower()

s.swapcase()

45. Determine whether the first letter of the string 'abCdEfg' is capitalized, whether all letters are lowercase, and whether all letters are uppercase.

s='abCdEfg'

s.istitle() # Whether the first letter is capitalized

s.isupper()

s.islower()

46. ​​Return the initial capitalization of the string 'this is python' and the initial capitalization of each word in the string.

s='this is python'

s.capitalize() # Capitalize the first letter

s.title() # Capitalize the first letter of each word in the string

47. Determine whether the string 'this is python' starts with 'this' and ends with 'python'.

s='this is python'

s.startswith('this') # whether this starts with

s.endswith('python')

48. Returns the number of occurrences of 'is' in the string 'this is python'.

s='this is python'

s.count('is')

49. Returns the position of the first and last occurrence of 'is' in the string 'this is python'.

s='this is python'

s.find('is') # find starts from the left

s.rfind('is') # rfind starts from the right and finds the last occurrence

50. Slice the string 'this is python' into 3 words.

'this is python'.split()

51. Return the result of the string 'blog.csdn.net/xufive/article/details/102946961' sliced ​​by the path separator.

'blog.csdn.net/xufive/article/details/102946961'.split('/')

52. After slicing the character string '2.72, 5, 7, 3.14' with half-width commas, convert each element into a floating point type or an integer.

s='2.72, 5, 7, 3.14'

lst = s.split(',')

lst2 = [eval(x) for x in lst]

53. Determine whether the string 'adS12K56' is completely alphanumeric, whether it is all numbers, whether it is all letters, or whether it is all ASCII codes.

s = 'adS12K56'

s.isalnum() # Whether it is all alphanumeric

s.isnumeric() # Whether it is all numbers

s.isalpha() # Whether it is all letters

s.isascii() # Whether all are ASCII codes

54. Replace 'is' with 'are' in the string 'there is python'.

s = 'there is python'.replace('is', 'are')

55. Clear the blank characters on the left and right sides of the string '\t python \n'.

s = '\t python \n'

s.strip()

56. Print three full English character strings (for example, 'ok', 'hello', 'thank you') on separate lines to achieve left-aligned, right-aligned and center-aligned effects.

for  s  in  ['ok', 'hello', 'thank you']:

    for  c  in ['<', '>', '^']:

        k='{:*'+c+'14}'

        print(k.format(s))

57. Print three strings (for example, 'Hello, I'm David', 'OK, ok', 'Nice to meet you') in separate lines to achieve left-aligned, right-aligned and centered effects.

* ditto

58. Fill the left side of the three strings '15', '127', '65535' with 0 to make them the same length.

for k  in  ['15', '127', '65535']:

    print('{:08d}'.format(eval(k)))

59. Extract the protocol name in the url string 'https://blog.csdn.net/xufive'.

s='https://blog.csdn.net/xufive'

s[:5]

or

k = s.index('/')

s[:k-1]

60. Connect each element in the list ['a', 'b', 'c'] with '|' to form a string.

'|'.join(['a','b','c'])

61. Add a half-width comma between two adjacent letters of the string 'abc' to generate a new string.

','.join(list('abc'))

62. Input a mobile phone number from the keyboard, and output a string like 'Mobile: 186 6677 7788'.

tel = input('tel=')

s='Mobile:{}'.format(tel)

63. Input the year, month, day, hour, minute, and second from the keyboard, and output a string in the form of '2019-05-01 12:00:00'.

t = input('Enter the year, month, day, hour, minute and second (space interval):')

s='{}-{}-{} {}:{}:{}'.format(*t.split())

print(s)

64. Given two floating point numbers 3.1415926 and 2.7182818, format the output string 'pi = 3.1416, e = 2.7183'.

t = eval(input('Enter two floating-point numbers (comma-separated):'))

s='pi={:.4f}, e={:.4f}'.format(*t)

print(s)

65. Formatted output of 0.00774592 and 356800000 as scientific notation strings.

print('{:e} {:e}'.format(0.00774592, 356800000))

66. Format the decimal integer 240 as an octal and hexadecimal string.

print('Octal {0:o} Hex {0:x}'.format(240))

67. Convert the decimal integer 240 to a binary, octal, or hexadecimal string.

print('binary{0:b}octal{0:o}hexadecimal{0:x}'.format(240))

68. Convert the string '10100' into an integer according to binary, octal, decimal, and hexadecimal.

int('10100', 2)

int('10100', 8)

int('10100') # default to decimal

int('10100', 16)

69. Find the sum of the binary integer 1010, the octal integer 65, the decimal integer 52, and the hexadecimal integer b4.

0b1010 + 0o65 + 52 + 0xb4

70. Convert each element in the list [0,1,2,3.14,'x',None,'',list(),{5}] to Boolean.

lst = [0,1,2,3.14,'x',None,'',list(),{5}]

lst2 = [bool(x) for x  in lst ]

71. Return the ASCII code value of characters 'a' and 'A'.

ord('a')

ord('A')

72. Return the characters whose ASCII code values ​​are 57 and 122.

chr(57)

chr(122)

73. Write the two-dimensional list [[0.468,0.975,0.446],[0.718,0.826,0.359]] into a csv format file named csv_data, and try to open it with excel.

lst = [[0.468,0.975,0.446],[0.718,0.826,0.359]]

f=open('csv_data.csv','w')

for  li  in  lst:

    s = ','.join([str(x) for x  in li])

    f.write(s+'\n')

f.close()

74. Read the two-dimensional list from the csv_data.csv file.

f=open('csv_data.csv')

lst = [ ]

for  line  in  f:

    li = line.split(',')

    li = [eval(x) for x in li]

    lst.append(li)

f.close()

print(lst)

75. Append the two-dimensional list [[1.468,1.975,1.446],[1.718,1.826,1.359]] to the csv_data.csv file, and then read all the data.

lst = [[0.468,0.975,0.446],[0.718,0.826,0.359]]

f=open('csv_data.csv','a+') # a+ append readable mode

for  li  in  lst:

    s = ','.join([str(x) for x  in li])

    f.write(s+'\n')

f.seek(0) # Move the file pointer to the head so that data can be read from the beginning

for  line  in  f:

    print(line)

f.close()

76. Swap the values ​​of the variables x and y.

x, y = y, x

77. Determine whether the given parameter x is an integer.

type(x) == int

78. Determine whether the given parameter x is a list or a tuple.

type(x)==list or  type(x)==tuple

79. Determine whether 'https://blog.csdn.net' starts with 'http://' or 'https://'. If so, return 'http' or 'https'; otherwise, return None.

def  fun(s):

    if s.startswith('http://'):

        return 'http'

    elif s.startswith('https://'):

        return 'https'

    else:

        return None

s = fun('https://blog.csdn.net')

80. Determine whether 'https://blog.csdn.net' ends with '.com' or '.net'. If so, return 'com' or 'net'; otherwise, return None.

def  fun(s):

    if s.endswith('.com'):

        return 'com'

    elif s.endswith('.net'):

        return 'net'

    else:

        return None

s = fun('https://blog.csdn.net')

81. Set the integers or floating-point numbers greater than 3 in the list [3,'a',5.2,4,{},9,[]] to 1, and the rest to 0.

lst = [3,'a',5.2,4,{},9,[] ]

li = [ ]

for  s  in  lst:

    if  (type(s)==int or type(s)==float) and s>3:

        li.append(1)

    else:

        li.append(0)

print

82. a, b are two numbers, return the smaller or the largest of them.

max(a,b)

min(a,b)

83. Find the most frequently occurring number in the list [8,5,2,4,3,6,5,5,1,4,5] and how many times it occurs.

from collections import Counter

lst = [8,5,2,4,3,6,5,5,1,4,5]

di = Counter(lst)

print('The most frequent number and frequency is:', di.most_common(1))

84. Convert the two-dimensional list [[1], ['a','b'], [2.3, 4.5, 6.7]] into a one-dimensional list.

lst = [[1], ['a','b'], [2.3, 4.5, 6.7]]

li = [ ]

for  x  in  lst:

    li.extend(x)

print

85. Convert a list of keys and values ​​of equal length into a dictionary.

lst1=['a','b','c']

lst2=[10,15,20]

di={k:v for k,v in zip(lst1,lst2)}

86. Rewrite the logical expression a > 10 and a < 20 using chained comparison operators.

10<a<20

87. Write a function to print the characters passed in by the function parameters 30 times at an interval of 0.1 seconds without line breaks, to achieve a typewriter-like effect.

import time

def  typewriter(c):

    for  x  in  range(30):

        print(c, end='')

        time.sleep(0.1)

typewriter('x')

88. Sum a list of numbers.

sum(lst)

89. Return the maximum and minimum values ​​in a list of numbers.

max(lst)

min(lst)

90. Calculate the 3.5 square of 5 and the cube root of 3.

5**3.5 or pow(5, 3.5)

3**(1/3) or pow(3, 1/3)

91. Round 3.1415926 to 5 decimal places.

x=3.1415926

round(x,5)

92. Determine whether two objects are the same in memory.

x  is y

93. Return the properties and methods of the given object x.

help(x)

you (x)

94. Evaluate the string expression '(2+3)*5'.

s='(2+3)*5'

print(eval(s))

95. Realize the code function contained in the string 'x={"name":"David", "age":18}'.

s = '{"name":"David", "age":18}'

x = eval(s) # Get dictionary variable x after conversion

96. Use the map function to find the cube root of each element in the list [2,3,4,5].

lst = [2,3,4,5]

list(map(lambda x:x**3, lst))

97. Global variables can be defined inside the function through the keyword _____ global ___________.

98. If there is no return statement in the function or the return statement does not carry any return value, then the return value of the function is _______ None __________.

99. Using the context management keyword _____with_________ can automatically manage the file object, no matter what the reason is to end the statement block in the keyword, it can ensure that the file is closed correctly.

100. It is known that x = [[1,3,3], [2,3,1]], then the expression

sorted(x, key=lambda item:item[0]+item[2]) is ____[[2, 3, 1], [1, 3, 3]]

Guess you like

Origin blog.csdn.net/Vivien_CC/article/details/118077160