Python len函数介绍及实例

559 阅读2分钟

Python len() Function Tutorial With Example For Beginners

len()函数 用于任何可迭代对象。它返回一个整数,即该可迭代对象的长度。

Python的长度

Python len() 是一个内置函数,用于返回任何可迭代对象的长度。它返回 String 的字符数;它返回listdictionary 中的元素总数。

语法

len(any iterable object)

唯一需要的参数是一个可迭代对象 ,可以是 list、String 或 dictionary。

Python 字符串长度

在 Python 中找到一个字符串的长度,可以使用 len() 函数。我们可以用下面的代码来计算字符串的长度。

# app.py

strA = 'AppDividend'
print(len(strA))

请看输出结果。

Python Len Built-In Function Tutorial With Example

输出结果是11,这意味着StringAppDividend 包含11个字符。

Python 列表长度

Python找到一个列表长度 ,使用 len() 函数。我们可以计算出List 的长度。计算 List 的长度意味着我们需要计算 List 有多少个元素。

请看下面的代码。

# app.py

listA = ['PlayStation', 'Xbox', 'PSP', 'Wii']
print(len(listA))

请看输出结果。

Calculate List Length in Python

Python 字典的长度

要在Python 中找到一个字典 的长度,可以使用 len() 函数。计算 dictionary 的长度意味着我们需要计算 dictionary 有多少个项目。

请看下面的代码。

# app.py

dictA = {
    'name': 'Krunal Lathiya',
    'university': 'GTU',
    'enrollmentno': 110470116021,
    'college': 'VVP Engineering College'
}
print(len(dictA))

请看下面的输出。

Calculate Length of Dictionary in Python

在 For 循环中使用 len() 函数

我们可以在For 循环中使用 len() 函数。让我们看看下面的例子。

# app.py

ben10 = ['Jetray', 'EchoEcho', 'AlienX','DiamondHead', 'SwampFire']
i = 0
for i in range(0, len(ben10)):
    print(ben10[i])

在上面的代码中,我们定义了一个List,然后从0到List的长度遍历了这个List。然后,我们逐一打印了这些外星人。

请看下面的输出。

Use len() function in For loop

本教程到此结束。