首页 > 解决方案 > 我想计算特定项目的数量

问题描述

我有这个处理列表的代码。这是代码:

for n in persoane_event:
    split_zi_i = n[1].split('-')
    split_zi_s = n[2].split('-')
    if n[0] == 1 and n[3] != 'L':
        n[3] = 'S1'
        if int(saptamani[0][0]) <= int(split_zi_i[2]) and int(saptamani[0][-1]) >= int(split_zi_s[2]):
            n[3] = 'L'
            print(n)

这是我现在从中得到的输出:

[1, '2020-06-1', '2020-06-1', 'L']
[1, '2020-06-2', '2020-06-2', 'L']
[1, '2020-06-3', '2020-06-3', 'L']
[1, '2020-06-4', '2020-06-4', 'L']
[1, '2020-06-5', '2020-06-5', 'L']
[1, '2020-06-6', '2020-06-6', 'L']
[1, '2020-06-7', '2020-06-7', 'L']

如您所见,此输出位于 for 循环中,我想要计算此循环的总数'L'。在这种情况下counter = n[3].count('L')如何print 7。我可以这样做吗?对不起,如果这是一个愚蠢的问题,我 1 个月前才开始用 python 编程。

标签: python

解决方案


您可以使用该len()函数来确定列表的长度,这是一个可以帮助您的示例,

list1 = ['physics', 'chemistry', 'maths']
print (len(list1))

list2 = list(range(5)) #creates list of numbers between 0-4
print (len(list2)) 

上面例子的输出是:

3
5

您必须访问以下网站才能了解python中的列表方法和功能:

https://www.tutorialspoint.com/python3/list_len.htm

https://www.programiz.com/python-programming/methods/list

https://www.tutorialspoint.com/python3/python_lists.htm


推荐阅读