Python List - 计算列表中元素的数量

我们有多种方法获取list中元素的数量

使用 len()

# Python len()
list1 = [1, 2, 3]
n = len(list1)
print("The length of list using len() is: ", n)

使用 for 循环

# using for loop
list2 = [1, 2, 3, 4, 5]

counter = 0
for i in list2:
    # incrementing counter
    counter = counter + 1

print("Length of list using for loop is : " + str(counter))

使用 length_hint()

# using length_hint
from operator import length_hint

# Initializing list
list3 = [1, 4, 5, 7, 8]

# Finding length of list
# using length_hint()
list_len_hint = length_hint(list3)

print("Length of list using length_hint() is : " + str(list_len_hint))

使用 sum()

# using sum()

# Initializing list
list4 = [1, 2, 3, 4, 5, 6]

# Finding length of list
# using sum()
list_len_sum = sum(1 for i in list4)

print("Length of list using sum() is : " + str(list_len_sum))

使用 Comprehension

# using a list comprehension
list5 = [1, 4, 5, 7, 8]

list_len_comp = sum(1 for _ in list5)

print("Length of list using list comprehension is : " + str(list_len_comp))

使用 recursion

# Define a function to count the number of elements in a list using recursion
def count_elements_recursion(lst):
    # Base case: if the list is empty, return 0
    if not lst:
        return 0
    # Recursive case: add 1 to the count of the remaining elements in the list
    return 1 + count_elements_recursion(lst[1:])


# Test the function with a sample list
list6 = [1, 2, 3, 4, 5, 6, 7, 8]
print("The length of the list is: " + str(count_elements_recursion(list6)))

使用 enumerate

# using enumerate function
list7 = [1, 4, 5, 7, 8]
l = 0
for i, a in enumerate(list7):
    l += 1
print(l)

使用 Collections

from collections import Counter

# Initializing list
list8 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Finding length of list using Counter()
list_len = sum(Counter(list8).values())

print("Length of list using Counter() is: " +  str(list_len))

你可能感兴趣的:(Python,练习册,python,list,开发语言)