当前位置:   article > 正文

Python-VBA函数之旅-len函数

len函数

目录

一、len函数的常见应用场景:

二、len函数使用注意事项:

三、如何用好len函数?

1、len函数:

1-1、Python:

1-2、VBA:

2、推荐阅读:

个人主页:神奇夜光杯-CSDN博客 



一、len函数的常见应用场景:

        len函数在Python中非常常用,它可以帮助我们获取各种数据类型的长度或大小,常见的应用场景有:

1、字符串处理:当你需要知道一个字符串的长度时,可以使用len()函数,这在验证用户输入、处理文本数据或进行字符串操作时非常有用。

2、列表和元组操作:当你需要知道一个字符串的长度时,可以使用len()函数,这在验证用户输入、处理文本数据或进行字符串操作时非常有用。

3、字典操作:字典是Python中存储键值对的数据结构,len()函数可以用于获取字典中的键值对数量,这在统计字典大小或进行迭代操作时非常有用。

4、集合操作:集合用于存储唯一的元素,使用len()函数可以方便地获取集合中元素的数量,这在检查集合大小、比较集合或进行集合运算时非常有用。

5、自定义对象:如果你创建了自定义对象,并希望len()函数能够返回该对象的某种属性或状态的“长度”,你可以在自定义类中实现`__len__()`方法。

6、文件和输入/输出:在处理文件或进行输入/输出操作时,len()函数可以用来获取读取或写入的数据长度,这对于监控数据传输、检查文件大小或进行数据处理时非常有用。

7、循环和迭代控制:在循环中,有时候需要根据序列的长度来控制循环的次数,len()函数在这里可以发挥重要作用。

8、动态分配空间:在某些需要动态分配空间的情况下,如创建特定长度的列表或数组时,len()可以用于预先知道需要多少空间。

9、调试和日志记录:在开发过程中,len()函数可以用于调试,帮助开发者了解数据的大小或结构;同时,它也可以用于日志记录,记录数据的大小变化。

10、性能分析和优化:在性能分析和优化过程中,了解数据结构的大小可以帮助你确定算法的效率,使用len()函数可以方便地获取数据的大小,从而进行性能分析和比较。

11、结合其他函数和方法使用:len()函数可以与Python中的其他函数和方法结合使用,以实现更复杂的操作。例如,你可以使用len()与条件语句、循环结构、列表推导式等结合,以完成各种任务。

        总之,len()函数在Python编程中的应用非常广泛,几乎在任何需要知道对象大小或长度的场景中都可以使用。

二、len函数使用注意事项:

        在Python中使用len()函数时,有一些注意事项需要牢记,以确保正确使用并避免潜在的问题。以下是一些关键的注意事项:

1、数据类型支持:len()函数只适用于那些定义了`__len__()`方法的对象,这通常包括序列类型(如字符串、列表、元组、字节和字节数组)和集合类型(如字典、集合和冻结集合),如果你尝试对不支持长度计算的对象使用len()函数,将会引发TypeError异常。

2、返回值类型:len()函数始终返回一个整数,表示对象的长度或元素数量,如果对象没有长度(例如整数或浮点数),则不能使用len()函数。

3、对象的实时状态:len()函数返回的是对象在调用时的长度或大小,如果对象在调用len()函数之后被修改(例如,列表的元素被添加或删除),那么你需要再次调用len()函数来获取新的长度。

4、性能考虑:对于非常大的对象,使用len()函数可能会导致性能问题,因为它可能需要遍历整个对象来确定长度,在处理大数据集时,请考虑其他可能的性能优化方法。

5、空对象:对于空对象(如空字符串、空列表或空字典),len()函数将返回0,这有助于在编写代码时检查对象是否为空。

6、自定义对象:如果你想对自定义对象使用len()函数,你需要在类中实现`__len__()`方法,这个方法应该返回一个整数,表示对象的“长度”或“大小”。

7、可变/不可变对象:对于可变对象(如列表),len()返回的是当前状态下的长度,如果你之后修改了对象(例如添加或删除元素),你需要再次调用len()函数来获取新的长度,对于不可变对象(如字符串或元组),一旦创建,它们的长度就不会改变,所以len()函数的返回值也不会变。

        总之,只有遵循这些注意事项,你才能更有效地使用len()函数,并避免在Python编程中遇到常见的问题。

三、如何用好len函数?

        要用好Python中的len()函数,首先要明确它的作用:返回对象的长度或项目数。为了充分发挥len()函数的功能,可以遵循以下几个建议:

1、明确数据类型:在使用len()函数之前,确保你了解对象的数据类型,虽然len()函数可以用于多种数据类型,但不同的数据类型可能有不同的解释。例如,对于字符串,len()返回字符数;对于列表或元组,返回元素数量;对于字典,返回键值对的数量。

2、检查对象是否为空:使用len()函数可以快速检查一个对象是否为空,如果len()返回0,那么对象就是空的,这对于条件判断和循环控制非常有用。

3、在循环和迭代中使用:在编写循环或迭代时,可以使用len()函数来确定需要迭代的次数。例如,在遍历列表或字符串时,你可以使用len()来确定循环的次数。

4、避免不必要的计算:虽然len()函数通常很快,但如果你在一个循环中多次调用它来获取相同的长度,那么这可能会导致不必要的性能开销,在这种情况下,最好将长度存储在一个变量中,并在循环中使用这个变量。

5、自定义对象支持:如果你正在处理自定义对象,并希望len()函数能够返回对象的某种长度或大小,你可以在自定义类中实现`__len__()`方法,这样,当你对该对象调用len()函数时,Python会自动调用你定义的`__len__()`方法。

6、结合其他函数和方法使用:len()函数可以与Python中的其他函数和方法结合使用,以实现更复杂的操作。例如,你可以使用len()`与条件语句、循环结构、列表推导式等结合,以完成各种任务。

7、注意返回值类型:len()函数始终返回一个整数,确保你在使用返回值时考虑到这一点,避免将其与其他非整数类型混淆。

1、len函数
1-1、Python:
  1. # 1.函数:len
  2. # 2.功能:用于获取可迭代对象的长度或元素个数
  3. # 3.语法:len(s)
  4. # 4.参数:s,要获取其长度或者元素个数的对象
  5. # 5.返回值:返回可迭代对象的长度或元素个数
  6. # 6.说明:
  7. # 7.示例:
  8. # 利用dir()函数获取函数的相关内置属性和方法
  9. print(dir(len))
  10. # ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
  11. # '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__',
  12. # '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__',
  13. # '__str__', '__subclasshook__', '__text_signature__']
  14. # 利用help()函数获取函数的文档信息
  15. help(len)
  16. # 应用一:字符串处理
  17. # 示例1:获取字符串长度
  18. string1 = "Hello, World!"
  19. length = len(string1)
  20. print(f"The length of the string '{string1}' is {length}.")
  21. # The length of the string 'Hello, World!' is 13.
  22. # 示例2:比较两个字符串的长度
  23. string2 = "Python"
  24. string3 = "Java"
  25. if len(string2) > len(string3):
  26. print(f"'{string2}' is longer than '{string3}'.")
  27. elif len(string2) < len(string3):
  28. print(f"'{string2}' is shorter than '{string3}'.")
  29. else:
  30. print(f"'{string2}' and '{string3}' are the same length.")
  31. # 'Python' is longer than 'Java'.
  32. # 示例3:处理字符串切片并获取长度
  33. string4 = "myelsaiswonderful"
  34. substring = string4[2:6] # Slicing the string from index 2 to 5 (excluding 6)
  35. substring_length = len(substring)
  36. print(f"The substring '{substring}' of '{string4}' has a length of {substring_length}.")
  37. # The substring 'elsa' of 'myelsaiswonderful' has a length of 4.
  38. # 示例4:统计字符串中某个字符的出现次数(通过转换为列表并计算长度)
  39. string5 = "mississippi"
  40. char_to_count = "i"
  41. count = len([char for char in string5 if char == char_to_count])
  42. print(f"The character '{char_to_count}' appears {count} times in '{string5}'.")
  43. # The character 'i' appears 4 times in 'mississippi'.
  44. # 示例5:处理字符串中的空格并获取非空格字符的长度
  45. string6 = "Hello, World! "
  46. string6_without_spaces = ''.join(string6.split()) # Remove spaces
  47. length_without_spaces = len(string6_without_spaces)
  48. print(f"The length of '{string6}' without spaces is {length_without_spaces}.")
  49. # The length of 'Hello, World! ' without spaces is 12.
  50. # 应用二:列表和元组操作
  51. # 示例1:获取列表长度
  52. my_list = [1, 2, 3, 4, 5]
  53. list_length = len(my_list)
  54. print(f"The length of the list {my_list} is {list_length}.")
  55. # The length of the list [1, 2, 3, 4, 5] is 5.
  56. # 示例2:比较两个列表的长度
  57. list1 = [1, 2, 3]
  58. list2 = ['a', 'b', 'c', 'd']
  59. if len(list1) > len(list2):
  60. print(f"List {list1} is longer than list {list2}.")
  61. elif len(list1) < len(list2):
  62. print(f"List {list1} is shorter than list {list2}.")
  63. else:
  64. print(f"Lists {list1} and {list2} are the same length.")
  65. # List [1, 2, 3] is shorter than list ['a', 'b', 'c', 'd'].
  66. # 示例3:处理列表切片并获取长度
  67. fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
  68. sliced_fruits = fruits[1:4] # Slicing the list from index 1 to 3 (excluding 4)
  69. sliced_length = len(sliced_fruits)
  70. print(f"The sliced list {sliced_fruits} has a length of {sliced_length}.")
  71. # The sliced list ['banana', 'cherry', 'date'] has a length of 3.
  72. # 示例4:列表中添加元素并查看长度变化
  73. numbers = [1, 2, 3]
  74. print(f"Initial length of the list {numbers} is {len(numbers)}.")
  75. numbers.append(4) # Add an element to the list
  76. print(f"After adding an element, the length of the list {numbers} is {len(numbers)}.")
  77. # Initial length of the list [1, 2, 3] is 3.
  78. # After adding an element, the length of the list [1, 2, 3, 4] is 4.
  79. # 示例5:使用列表推导式并获取长度
  80. squares = [x**2 for x in range(5)] # List comprehension to create a list of squares
  81. squares_length = len(squares)
  82. print(f"The list {squares} of squares has a length of {squares_length}.")
  83. # The list [0, 1, 4, 9, 16] of squares has a length of 5.
  84. # 示例6:获取元组长度
  85. my_tuple = (10, 20, 30, 40, 50)
  86. tuple_length = len(my_tuple)
  87. print(f"The length of the tuple {my_tuple} is {tuple_length}.")
  88. # The length of the tuple (10, 20, 30, 40, 50) is 5.
  89. # 示例7:比较元组与列表的长度
  90. my_tuple = ('a', 'b', 'c')
  91. my_list = ['x', 'y', 'z']
  92. if len(my_tuple) == len(my_list):
  93. print(f"The tuple {my_tuple} and the list {my_list} are the same length.")
  94. else:
  95. print(f"The tuple {my_tuple} and the list {my_list} are not the same length.")
  96. # The tuple ('a', 'b', 'c') and the list ['x', 'y', 'z'] are the same length.
  97. # 应用三:字典操作
  98. # 示例1:获取字典的长度(键的数量)
  99. my_dict = {'a': 1, 'b': 2, 'c': 3}
  100. dict_length = len(my_dict)
  101. print(f"The length of the dictionary {my_dict} is {dict_length}.")
  102. # The length of the dictionary {'a': 1, 'b': 2, 'c': 3} is 3.
  103. # 示例2:比较两个字典的长度
  104. dict1 = {'x': 10, 'y': 20}
  105. dict2 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
  106. if len(dict1) > len(dict2):
  107. print(f"Dictionary {dict1} has more keys than {dict2}.")
  108. elif len(dict1) < len(dict2):
  109. print(f"Dictionary {dict1} has fewer keys than {dict2}.")
  110. else:
  111. print(f"Dictionaries {dict1} and {dict2} have the same number of keys.")
  112. # Dictionary {'x': 10, 'y': 20} has fewer keys than {'a': 1, 'b': 2, 'c': 3, 'd': 4}.
  113. # 示例3:添加键值对到字典并查看长度变化
  114. person = {'name': 'Myelsa', 'age': 18}
  115. print(f"Initial length of the dictionary {person} is {len(person)}.")
  116. person['city'] = 'New York' # Add a key-value pair to the dictionary
  117. print(f"After adding a key-value pair, the length of the dictionary {person} is {len(person)}.")
  118. # Initial length of the dictionary {'name': 'Myelsa', 'age': 18} is 2.
  119. # After adding a key-value pair, the length of the dictionary {'name': 'Myelsa', 'age': 18, 'city': 'New York'} is 3.
  120. # 示例4:移除字典中的键值对并查看长度变化
  121. person = {'name': 'Myelsa', 'age': 18, 'city': 'Guangzhou'}
  122. print(f"Initial length of the dictionary {person} is {len(person)}.")
  123. del person['city'] # Remove a key-value pair from the dictionary
  124. print(f"After removing a key-value pair, the length of the dictionary {person} is {len(person)}.")
  125. # Initial length of the dictionary {'name': 'Myelsa', 'age': 18, 'city': 'Guangzhou'} is 3.
  126. # After removing a key-value pair, the length of the dictionary {'name': 'Myelsa', 'age': 18} is 2.
  127. # 示例5:获取字典中值的数量(不考虑重复)
  128. my_dict = {'a': 1, 'b': 2, 'c': 1, 'd': 3}
  129. values_set = set(my_dict.values()) # Convert values to a set to remove duplicates
  130. values_count = len(values_set)
  131. print(f"The number of unique values in the dictionary {my_dict} is {values_count}.")
  132. # The number of unique values in the dictionary {'a': 1, 'b': 2, 'c': 1, 'd': 3} is 3.
  133. # 示例6:比较两个字典是否有相同数量的键值对
  134. dict3 = {'e': 5, 'f': 6}
  135. dict4 = {'g': 7, 'h': 8, 'i': 9}
  136. if len(dict3) == len(dict4):
  137. print(f"Dictionaries {dict3} and {dict4} have the same number of key-value pairs.")
  138. else:
  139. print(f"Dictionaries {dict3} and {dict4} do not have the same number of key-value pairs.")
  140. # Dictionaries {'e': 5, 'f': 6} and {'g': 7, 'h': 8, 'i': 9} do not have the same number of key-value pairs.
  141. # 应用四:集合操作
  142. # 示例1:获取集合的长度(元素数量)
  143. my_set = {1, 2, 3, 4, 5}
  144. set_length = len(my_set)
  145. print(f"The length of the set {my_set} is {set_length}.")
  146. # The length of the set {1, 2, 3, 4, 5} is 5.
  147. # 示例2:比较两个集合的长度
  148. set1 = {1, 2, 3}
  149. set2 = {4, 5, 6, 7}
  150. if len(set1) > len(set2):
  151. print(f"Set {set1} has more elements than {set2}.")
  152. elif len(set1) < len(set2):
  153. print(f"Set {set1} has fewer elements than {set2}.")
  154. else:
  155. print(f"Sets {set1} and {set2} have the same number of elements.")
  156. # Set {1, 2, 3} has fewer elements than {4, 5, 6, 7}.
  157. # 示例3:添加元素到集合并查看长度变化
  158. my_set = {1, 2, 3}
  159. print(f"Initial length of the set {my_set} is {len(my_set)}.")
  160. my_set.add(4) # Add an element to the set
  161. print(f"After adding an element, the length of the set {my_set} is {len(my_set)}.")
  162. # Initial length of the set {1, 2, 3} is 3.
  163. # After adding an element, the length of the set {1, 2, 3, 4} is 4.
  164. # 示例4:移除集合中的元素并查看长度变化
  165. my_set = {1, 2, 3, 4}
  166. print(f"Initial length of the set {my_set} is {len(my_set)}.")
  167. my_set.remove(3) # Remove an element from the set
  168. print(f"After removing an element, the length of the set {my_set} is {len(my_set)}.")
  169. # Initial length of the set {1, 2, 3, 4} is 4.
  170. # After removing an element, the length of the set {1, 2, 4} is 3.
  171. # 示例5:计算两个集合的并集并获取长度
  172. set1 = {1, 2, 3}
  173. set2 = {3, 4, 5}
  174. union_set = set1.union(set2) # Get the union of two sets
  175. union_length = len(union_set)
  176. print(f"The union of {set1} and {set2} is {union_set} and its length is {union_length}.")
  177. # The union of {1, 2, 3} and {3, 4, 5} is {1, 2, 3, 4, 5} and its length is 5.
  178. # 示例6:计算两个集合的交集并获取长度
  179. set1 = {1, 2, 3}
  180. set2 = {3, 4, 5}
  181. intersection_set = set1.intersection(set2) # Get the intersection of two sets
  182. intersection_length = len(intersection_set)
  183. print(f"The intersection of {set1} and {set2} is {intersection_set} and its length is {intersection_length}.")
  184. # The intersection of {1, 2, 3} and {3, 4, 5} is {3} and its length is 1.
  185. # 应用五:自定义对象
  186. # 示例1:自定义一个字符串列表类,并实现__len__()方法
  187. class StringList:
  188. def __init__(self, strings):
  189. self.strings = strings
  190. def __len__(self):
  191. return len(self.strings)
  192. def __str__(self):
  193. return str(self.strings)
  194. # 创建一个StringList对象
  195. my_list = StringList(['apple', 'banana', 'cherry'])
  196. # 使用len()函数获取StringList对象的长度
  197. length = len(my_list)
  198. print(f"The length of the StringList {my_list} is {length}.")
  199. # The length of the StringList ['apple', 'banana', 'cherry'] is 3.
  200. # 示例2:自定义一个学生类,每个学生有多个课程,计算学生选课数量
  201. class Student:
  202. def __init__(self, name, courses):
  203. self.name = name
  204. self.courses = courses
  205. def __len__(self):
  206. return len(self.courses)
  207. def __str__(self):
  208. return f"{self.name} has {len(self.courses)} courses."
  209. # 创建一个Student对象
  210. student = Student("Myelsa", ["Math", "Science", "English"])
  211. # 使用len()函数获取Student对象的课程数量
  212. num_courses = len(student)
  213. print(f"The number of courses for {student} is {num_courses}.")
  214. # The number of courses for Myelsa has 3 courses. is 3.
  215. # 示例3:自定义一个点集类,计算点集中点的数量
  216. class PointSet:
  217. def __init__(self, points):
  218. self.points = points
  219. def __len__(self):
  220. return len(self.points)
  221. def __str__(self):
  222. return str(self.points)
  223. # 创建一个PointSet对象
  224. point_set = PointSet([(1, 2), (3, 4), (5, 6)])
  225. # 使用len()函数获取PointSet对象的点数量
  226. num_points = len(point_set)
  227. print(f"The number of points in the PointSet {point_set} is {num_points}.")
  228. # The number of points in the PointSet [(1, 2), (3, 4), (5, 6)] is 3.
  229. # 应用六:文件和输入/输出
  230. # 示例1:读取文件内容并计算其长度
  231. # 打开文件并读取所有内容
  232. with open('file.txt', 'r', encoding='utf-8') as file:
  233. content = file.read()
  234. # 计算文件内容的长度
  235. content_length = len(content)
  236. print(f"The length of the file content is: {content_length} characters.")
  237. # The length of the file content is: 39 characters.
  238. # 示例2:逐行读取文件并计算行数
  239. # 打开文件并逐行读取
  240. with open('file.txt', 'r', encoding='utf-8') as file:
  241. lines = file.readlines()
  242. # 计算行数(即列表长度)
  243. num_lines = len(lines)
  244. print(f"The number of lines in the file is: {num_lines}.")
  245. # The number of lines in the file is: 6.
  246. # 示例3:从用户输入读取字符串并计算其长度
  247. # 从用户获取输入
  248. user_input = input("Enter a string: ")
  249. # 计算输入字符串的长度
  250. input_length = len(user_input)
  251. print(f"The length of your input is: {input_length} characters.")
  252. # Enter a string: myelsa
  253. # The length of your input is: 6 characters.
  254. # 示例4:将文件内容读入列表并计算列表中元素的数量
  255. # 打开文件并读取所有行,将每行转换为整数并添加到列表中
  256. with open('file.txt', 'r', encoding='utf-8') as file:
  257. data_list = [int(line.strip()) for line in file]
  258. # 计算列表中元素的数量
  259. num_elements = len(data_list)
  260. print(f"The number of elements in the list is: {num_elements}.")
  261. # The number of elements in the list is: 6.
  262. # 应用七:循环和迭代控制
  263. # 示例1:使用len()和for循环遍历列表
  264. my_list = [1, 2, 3, 4, 5]
  265. # 使用len()获取列表长度,并使用for循环遍历列表
  266. for i in range(len(my_list)):
  267. print(my_list[i])
  268. # 1
  269. # 2
  270. # 3
  271. # 4
  272. # 5
  273. # 示例2:使用len()和while循环遍历字符串
  274. my_string = "Hello, Python!"
  275. index = 0
  276. # 使用len()获取字符串长度,并使用while循环遍历字符串
  277. while index < len(my_string):
  278. print(my_string[index])
  279. index += 1
  280. # H
  281. # e
  282. # l
  283. # l
  284. # o
  285. # ,
  286. #
  287. # P
  288. # y
  289. # t
  290. # h
  291. # o
  292. # n
  293. # !
  294. # 示例3:使用len()和列表推导式(迭代控制)
  295. my_list = [1, 2, 3, 4, 5]
  296. # 使用len()和列表推导式创建一个新列表,包含原列表中每个元素的平方
  297. squared_list = [x ** 2 for x in my_list if x < len(my_list)]
  298. print(squared_list)
  299. # [1, 4, 9, 16]
  300. # 示例4:使用len()和enumerate()函数遍历列表同时获取索引和值
  301. my_list = ['apple', 'banana', 'cherry']
  302. # 使用enumerate()和len()来遍历列表,并打印索引和值
  303. for index, item in enumerate(my_list):
  304. print(f"Index {index} has value {item}")
  305. # 也可以使用range()和len()来达到相同的效果
  306. for index in range(len(my_list)):
  307. print(f"Index {index} has value {my_list[index]}")
  308. # Index 0 has value apple
  309. # Index 1 has value banana
  310. # Index 2 has value cherry
  311. # Index 0 has value apple
  312. # Index 1 has value banana
  313. # Index 2 has value cherry
  314. # 示例5:使用len()控制循环次数以处理嵌套列表
  315. nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  316. # 使用len()来控制外部循环,遍历嵌套列表的每一个子列表
  317. for i in range(len(nested_list)):
  318. # 使用len()来控制内部循环,遍历当前子列表的每一个元素
  319. for j in range(len(nested_list[i])):
  320. print(nested_list[i][j])
  321. # 1
  322. # 2
  323. # 3
  324. # 4
  325. # 5
  326. # 6
  327. # 7
  328. # 8
  329. # 9
  330. # 应用八:动态分配空间
  331. # 示例1:根据输入字符串的长度动态创建列表
  332. input_string = input("Enter a string: ")
  333. # 使用len()获取输入字符串的长度,并创建一个相应长度的列表
  334. list_length = len(input_string)
  335. my_list = [None] * list_length
  336. # 现在可以根据需要填充列表
  337. for i in range(list_length):
  338. my_list[i] = input_string[i]
  339. print(my_list)
  340. # Enter a string: myelsa
  341. # ['m', 'y', 'e', 'l', 's', 'a']
  342. # 示例2:根据一组数字动态创建和填充字典
  343. numbers = input("Enter numbers separated by spaces: ").split()
  344. # 使用len()获取数字的数量,并创建一个空字典
  345. num_count = len(numbers)
  346. my_dict = {}
  347. # 根据数字的数量动态添加键值对到字典中
  348. for i in range(num_count):
  349. my_dict[i] = int(numbers[i])
  350. print(my_dict)
  351. # Enter numbers separated by spaces: 16
  352. # {0: 16}
  353. # 示例3:动态扩展列表以包含新元素
  354. my_list = [1, 2, 3]
  355. # 假设我们要添加一个新元素到列表末尾
  356. new_element = 4
  357. # 不需要直接使用len()来分配空间,Python列表会自动处理
  358. my_list.append(new_element)
  359. print(my_list)
  360. # [1, 2, 3, 4]
  361. # 应用九:调试和日志记录
  362. # 示例1:使用print和len()进行基本调试
  363. my_list = [1, 2, 3, 4, 5]
  364. # 在调试时使用print和len()查看列表长度
  365. print(f"The length of my_list is: {len(my_list)}")
  366. # 对列表进行修改后,再次查看长度
  367. my_list.append(6)
  368. print(f"After appending an element, the length of my_list is: {len(my_list)}")
  369. # The length of my_list is: 5
  370. # After appending an element, the length of my_list is: 6
  371. # 示例2:使用日志库(如logging)记录长度信息
  372. import logging
  373. # 配置日志记录器
  374. logging.basicConfig(level=logging.INFO)
  375. my_list = [1, 2, 3, 4, 5]
  376. # 使用logging库记录列表长度
  377. logging.info(f"The length of my_list is: {len(my_list)}")
  378. # 对列表进行修改,并记录修改后的长度
  379. my_list.append(6)
  380. logging.info(f"After appending an element, the length of my_list is: {len(my_list)}")
  381. # INFO:root:The length of my_list is: 5
  382. # INFO:root:After appending an element, the length of my_list is: 6
  383. # 示例3:在复杂函数中使用len()进行调试
  384. import logging
  385. def process_data(data):
  386. # 假设data是一个列表,我们对其进行一些处理
  387. processed_data = [x * 2 for x in data]
  388. # 使用logging记录处理前和处理后的数据长度
  389. logging.debug(f"Original data length: {len(data)}")
  390. logging.debug(f"Processed data length: {len(processed_data)}")
  391. return processed_data
  392. # 示例数据
  393. data = [1, 2, 3]
  394. # 调用函数并记录日志
  395. processed_data = process_data(data)
  396. logging.info(f"Processed data: {processed_data}")
  397. # 示例4:在异常处理中使用len()进行调试
  398. import logging
  399. def read_file_and_process(filename):
  400. try:
  401. with open(filename, 'r') as file:
  402. lines = file.readlines()
  403. # 使用len()检查是否读取到任何行
  404. if len(lines) == 0:
  405. raise ValueError("The file is empty.")
  406. # 对读取到的行进行处理(此处仅为示例,未实际处理)
  407. except FileNotFoundError:
  408. logging.error(f"File {filename} not found.")
  409. except ValueError as e:
  410. logging.error(e)
  411. except Exception as e:
  412. logging.error(f"An error occurred: {e}")
  413. logging.debug(f"Number of lines read: {len(lines) if 'lines' in locals() else 'N/A'}")
  414. # 调用函数,假设文件存在但为空
  415. read_file_and_process('file.txt')
  416. # 应用十:性能分析和优化
  417. # 示例1:避免在循环中多次调用len()
  418. # 不推荐的做法:在循环中多次调用len()
  419. my_list = [1, 2, 3, 4, 5]
  420. for i in range(len(my_list)):
  421. print(len(my_list)) # 这里的len()调用是不必要的,因为列表长度不会改变
  422. print(my_list[i])
  423. # 推荐的做法:在循环外部调用len(),并存储结果
  424. list_length = len(my_list)
  425. for i in range(list_length):
  426. print(list_length) # 使用之前存储的长度
  427. print(my_list[i])
  428. # 示例2:使用生成器代替列表以节省内存
  429. # 使用列表推导式创建列表
  430. my_list = [x * x for x in range(1000000)] # 这会立即创建一个大列表,占用大量内存
  431. print(len(my_list)) # 使用len()获取长度
  432. # 使用生成器表达式节省内存
  433. my_generator = (x * x for x in range(1000000)) # 生成器不会立即创建所有元素,而是按需生成
  434. print(sum(1 for _ in my_generator)) # 使用sum和生成器表达式计算元素数量,而不是len()
  435. # 示例3:使用内置函数和库函数代替手动循环
  436. # 使用循环和len()计算列表中所有元素的和
  437. my_list = [1, 2, 3, 4, 5]
  438. sum_manual = 0
  439. for item in my_list:
  440. sum_manual += item
  441. print(sum_manual)
  442. # 使用内置函数sum()代替循环,更高效
  443. sum_builtin = sum(my_list)
  444. print(sum_builtin)
  445. # 对于更复杂的操作,考虑使用NumPy等库,它们针对数组操作进行了优化
  446. import numpy as np
  447. my_array = np.array(my_list)
  448. sum_numpy = np.sum(my_array)
  449. print(sum_numpy)
  450. # 示例4:性能分析使用time模块测量执行时间
  451. import time
  452. # 示例函数,使用len()
  453. def count_elements(data):
  454. return len(data)
  455. # 创建一个大型数据集
  456. large_data = [x for x in range(1000000)]
  457. # 使用time模块测量函数执行时间
  458. start_time = time.time()
  459. count = count_elements(large_data)
  460. end_time = time.time()
  461. print(f"Number of elements: {count}")
  462. print(f"Execution time: {end_time - start_time} seconds")
  463. # Number of elements: 1000000
  464. # Execution time: 0.0 seconds
  465. # 示例5:使用cProfile进行性能分析
  466. import cProfile
  467. # 示例函数,执行一些操作并返回长度
  468. def process_data(data):
  469. processed_data = [x * x for x in data]
  470. return len(processed_data)
  471. # 创建一个大型数据集
  472. large_data = [x for x in range(100000)]
  473. # 使用cProfile进行性能分析
  474. cProfile.run('process_data(large_data)')
  475. # 应用十一:结合其他函数和方法使用
  476. # 示例1:验证列表长度是否符合预期
  477. def validate_list_length(lst, expected_length):
  478. if len(lst) != expected_length:
  479. raise ValueError(f"Expected list length {expected_length}, but got {len(lst)}")
  480. return lst
  481. my_list = [1, 2, 3, 4]
  482. try:
  483. validate_list_length(my_list, 5)
  484. except ValueError as e:
  485. print(e)
  486. # Expected list length 5, but got 4
  487. # 示例2:使用map()函数和len()计算列表中每个字符串的长度
  488. my_strings = ['hello', 'world', 'python']
  489. lengths = list(map(len, my_strings))
  490. print(lengths)
  491. # [5, 5, 6]
  492. # 示例3:使用filter()函数和len()筛选长度大于特定值的字符串
  493. my_strings = ['a', 'apple', 'banana', 'c', 'cherry']
  494. long_strings = list(filter(lambda s: len(s) > 1, my_strings))
  495. print(long_strings) # 输出: ['apple', 'banana', 'cherry']
  496. # ['apple', 'banana', 'cherry']
  497. # 示例4:使用sorted()函数和len()按字符串长度排序
  498. my_strings = ['apple', 'cherry', 'banana', 'grape']
  499. sorted_by_length = sorted(my_strings, key=len)
  500. print(sorted_by_length)
  501. # ['apple', 'grape', 'cherry', 'banana']
  502. # 示例5:使用reduce()函数和len()计算嵌套列表中所有字符串的总长度
  503. from functools import reduce
  504. nested_list = [['a', 'bc'], ['def', 'ghi'], ['jklmnop']]
  505. total_length = reduce(lambda acc, lst: acc + sum(map(len, lst)), nested_list, 0)
  506. print(total_length)
  507. # 16
  508. # 示例6:在数据清洗过程中使用len()去除空字符串
  509. data = ['apple', '', 'banana', ' ', 'cherry']
  510. cleaned_data = [item for item in data if len(item.strip()) > 0]
  511. print(cleaned_data)
  512. # ['apple', 'banana', 'cherry']
1-2、VBA
略,待后补。
2、推荐阅读:

1、Python-VBA函数之旅-iter()函数

Python算法之旅:Algorithm

Python函数之旅:Functions 

个人主页:https://blog.csdn.net/ygb_1024?spm=1010.2135.3001.5421 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/661882
推荐阅读
相关标签
  

闽ICP备14008679号