程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

For example the len() function in Python

編輯:Python

Python 中的 len() Function is super convenient,Are you in the process is often used when a function.len()Input is a sequence or a collection of,當函數被調用時,It returns the length of the.你可以使用 len() To get you in Python Anything you want in the length of the.例如,It can be used for string、列表、Figure and a dictionary.另一個使用 len() A good example of this is with loop or range() 函數結合使用.現在讓我們看看使用len()函數的幾種方法.


在字符串中使用len()函數

首先很簡單,我們可以用**len()**To check the length of a string.The following are examples of a few do this.

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('[email protected]#$'))
復制代碼
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()實際例子

在下面的例子中,We will be a string of Numbers stored as a string,To indicate that the zip code.我們可以使用len()To determine the length of the zip code is correct.Because all the zip need to be5個字符的長度,我們可以使用len()To determine if a given zip code is valid or invalid.

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() Function is super useful.In simple and complex applications,There are countless examples show that you need to know the length of a list.下面是幾個使用 len() With the list of examples of.

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()

在下面的例子中,We have a list of the tools in the yard.We can cycle on each yard tools name,並使用 len() The length of a function to print out each tool.

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.
復制代碼

List comprehensions of thelen()函數

len() 函數在 Python 的列表理解Also is very good.

rivers = ['Amazon', 'Nile', 'Yangtze']
print([len(river) for river in rivers])
復制代碼
[6, 4, 7]
復制代碼

使用 len() 與 range()

This example shows how to len() 函數與 Python range() 函數一起使用.這是一種有用的方法,Because the cycle of code can access the variable i Index and the index of value.使用 len() 和 range() 的好處是,How many items no matter list,The code can be accurately iterative them,Without the need to counter.

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
復制代碼

請注意,When we change the list size here,Code still can correctly handle it.

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()Calculate the command lineargs

len()Function of the ingenious use of let we can calculate to aPythonThe number of file on the command line parameters.We can calculate all the total length of the command line parameters.

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()In figure yuan、A dictionary and a collection of relations

你也可以將 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() 函數總結

We have seen a lot about how to use in different ways len() 函數的例子.You will find yourself on your Python In the program have been using this convenient function.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved