侧边栏壁纸
  • 累计撰写 48 篇文章
  • 累计创建 33 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

Python计算长度

Angus
2023-08-17 / 0 评论 / 0 点赞 / 80 阅读 / 933 字

在 Python 中,可以使用 len() 函数来计算数组(或其他可迭代对象)的长度。 下面是一些示例代码:

  1. 计算列表的长度:
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)  # 输出:5
  1. 计算字符串的长度:
my_string = "Hello, world!"
length = len(my_string)
print(length)  # 输出:13
  1. 计算元组的长度:
my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple)
print(length)  # 输出:5
  1. 计算字典的长度(即键值对的数量):
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
length = len(my_dict)
print(length)  # 输出:3

无论是列表、字符串、元组还是字典,都可以使用 len() 函数来获取其长度。在处理字符串时,len() 函数返回的是字符串中字符的数量。

0

评论区