Python 中的 len() 函数超级方便,是你在制作程序时经常会用到的一个函数。len()的输入是一个序列或一个集合,当函数被调用时,它返回长度。你可以使用 len() 来获得你在 Python 中想要的任何东西的长度。例如,它可以用于字符串、列表、图元和字典。另一个使用 len() 的好例子是与循环或 range() 函数结合使用。现在让我们看看使用len()函数的几种方法。
在字符串中使用len()函数
首先很简单,我们可以用**len()**来检查一个字符串的长度。下面是几个这样做的例子。
print(len(''))
0
print(len(' '))
1
print(len('Hi!'))
3
print(len('This string is a little longer.'))
31
print(len('Python'))
6
print(len('Programming'))
11
print(len('!@#$'))
4
my_name = 'Vegibit'
print('The length of your name is: ', end='')
print(len(my_name))
The length of your name is: 7
best_language_ever = 'Python'
print(len(best_language_ever))
6
字符串的len()实际例子
在下面的例子中,我们将一串数字存储为一个字符串,以表示邮政编码。我们可以使用len()来确定邮政编码的长度是否正确。由于所有的邮编都需要5个字符的长度,我们可以使用len()来确定一个给定的邮编是有效还是无效的。
zip_code = '10001'
if len(zip_code) == 5:
check = 'Valid'
else:
check = 'Invalid'
print(check)
Valid
zip_code = '1234567'
if len(zip_code) == 5:
check = 'Valid'
else:
check = 'Invalid'
print(check)
Invalid
zip_code = '94088'
check = 'Valid' if len(zip_code) == 5 else 'Invalid'
print(check)
Valid
在列表中使用len()函数
在 Python 中处理列表时,len() 函数超级有用。在简单和复杂的程序中,有无数的例子表明你需要知道一个列表的长度。下面是几个使用 len() 与列表的例子。
animals = ['rabbit', 'dog', 'moose']
print(len(animals))
3
sodas = ['Coke', 'Pepsi', 'Sprite']
print(len(sodas))
3
quarterly_revenues = [15000, 12000, 9000, 20000]
print(len(quarterly_revenues))
4
stock_prices = [343.26, 89.25]
print(len(stock_prices))
2
user_settings = [True, False, False, True, False]
print(len(user_settings))
5
列表的 len() 实例
dog_names = []
while True:
print('What is dog name number ' + str(len(dog_names) + 1) + '? ("q" to quit):')
name = input()
if name == 'q':
break
dog_names = dog_names + [name]
print('You entered ' + str(len(dog_names)) + ' dog names.')
print('Here they are for you:')
for name in dog_names:
print(' ' + name)
What is dog name number 1? ("q" to quit):
Moe
What is dog name number 2? ("q" to quit):
Buddy
What is dog name number 3? ("q" to quit):
Winnie
What is dog name number 4? ("q" to quit):
q
You entered 3 dog names.
Here they are for you:
Moe
Buddy
Winnie
在一个循环中使用 len()
在下面的例子中,我们有一个院子里的工具列表。我们可以在每个院子工具的名称上循环,并使用 len() 函数打印出每个工具的长度。
yard_tools = ['Snow blower', 'Tractor', 'Lawn Mower']
for yard_tool in yard_tools:
print(yard_tool + ' has ' + str(len(yard_tool)) + ' characters')
Snow blower has 11 characters
Tractor has 7 characters
Lawn Mower has 10 characters
我们可以用 Simpsons 和 f-strings 做类似的事情。
the_simpsons = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie']
for character in the_simpsons:
print(f'{character} has a total of {len(character)} characters.')
Homer has a total of 5 characters.
Marge has a total of 5 characters.
Bart has a total of 4 characters.
Lisa has a total of 4 characters.
Maggie has a total of 6 characters.
列表理解中的len()函数
len() 函数在 Python 的列表理解中也很好用。
rivers = ['Amazon', 'Nile', 'Yangtze']
print([len(river) for river in rivers])
[6, 4, 7]
使用 len() 与 range()
这个例子展示了如何将 len() 函数与 Python range() 函数一起使用。这是一种有用的方法,因为循环中的代码可以访问变量 i 索引以及索引处的值。使用 len() 和 range() 的好处是,无论列表中的项目有多少,代码都能准确地迭代它们,而不需要计数器。
gifts = ['Gaming PC', 'Ceiling Fan', 'Nintendo Watch']
for i in range(len(gifts)):
print('Index ' + str(i) + ' in gifts is: ' + gifts[i])
Index 0 in gifts is: Gaming PC
Index 1 in gifts is: Ceiling Fan
Index 2 in gifts is: Nintendo Watch
请注意,当我们在这里改变列表的大小时,代码仍然能正确地处理它。
gifts = ['Gaming PC', 'Ceiling Fan', 'Nintendo Watch', 'More Gifts!', 'Even More Gifts!!']
for i in range(len(gifts)):
print('Index ' + str(i) + ' in gifts is: ' + gifts[i])
Index 0 in gifts is: Gaming PC
Index 1 in gifts is: Ceiling Fan
Index 2 in gifts is: Nintendo Watch
Index 3 in gifts is: More Gifts!
Index 4 in gifts is: Even More Gifts!!
用len()计算命令行的args
len()函数的这一巧妙使用让我们可以计算传给一个Python文件的命令行参数的数量。我们还可以计算所有命令行参数的总长度。
import sys
# printing the number of arguments
print(f'You passed {len(sys.argv[1:])} arguments to the {sys.argv[0]} file.')
# adding the length of all command line arguments
word_lengths = 0
for arg in sys.argv[1:]:
word_lengths += len(arg)
print(f'The total length of all command-line arguments is {word_lengths}')
PS C:\Python> python testing.py 1 2
You passed 2 arguments to the testing.py file.
The total length of all command-line arguments is 2
PS C:\Python> python testing.py 'hi' 'ho' 'silver'
You passed 3 arguments to the testing.py file.
The total length of all command-line arguments is 10
len()与图元、字典和集合的关系
你也可以将 len() 函数与 tuple、dictionary 和 set 数据类型一起使用。这里有几个例子。
# len of tuples
eggs = ('hello', 42, 0.5, True, False)
print(len(eggs))
5
# len of dictionaries
ice_cream_preferences = {
'Ben': 'Chocolate',
'Jerry': 'Vanilla',
'Sandy': 'Cookie Dough',
'Mary': 'Black Rasberry'
}
print(len(ice_cream_preferences))
4
# len of sets
stocks = {'MSFT', 'FB', 'IBM', 'FB'}
print(len(stocks))
3
Python len() 函数总结
我们已经看到了很多关于如何以不同方式使用 len() 函数的例子。你会发现自己在你的 Python 程序中一直在使用这个方便的函数。