简体   繁体   English

Python:计算列表中的项目组

[英]Python: Counting Groups of Items in a List

I am working on learning Python via Codecademy and I am struggling to figure out why I am getting a return of 1 when I run this query. 我正在通过Codecademy学习Python,我正在努力弄清楚为什么我在运行此查询时得到1的返回值。 Note: I know I could do a sequence.count(item) but I am trying to do this without the count function. 注意:我知道我可以做一个sequence.count(item)但是我试图在没有count函数的情况下这样做。 Any help would be appreciated. 任何帮助,将不胜感激。

def count(sequence, item):
    rep = int(0)
    for item in sequence:
        if item in sequence:
            rep += 1
        else:
            rep = 0
    return rep

print count([1], 7)

I think you confused yourself by using "item" to refer to two different things. 我认为你通过使用“item”来引用两个不同的东西让你感到困惑。 I changed the loop variable to i . 我将循环变量更改为i

def count(sequence, item):
    rep = 0
    for i in sequence:
        if i == item:
            rep += 1
    return rep

print count([1], 7)

Also, you probably don't want to keep setting rep to 0 此外,您可能不希望将rep设置为0

Corrected function: 更正功能:

def count(sequence, item):
    rep = 0
    for i in sequence:
        if i == item:
            rep += 1
    return rep

Regarding these lines: 关于这些线:

for item in sequence:
    if item in sequence:

When you input [1] into the function, it goes: 当您在函数中输入[1] ,它会:

  • for item in sequence (first and only item is 1 ) for item in sequence (第一个和唯一的项目是1

  • if item is in sequence ( if 1 is in the sequence... which it is) if item is in sequence (如果1在序列中......它是)

  • then rep += 1 , hence 1 is returned 然后rep += 1 ,因此返回1

for item in sequence means for each item in the sequence , do something. for item in sequence是指每个itemsequence ,做一些事情。 In your case you are merely confirming that the item is indeed in the sequence. 在您的情况下,您只是确认该项目确实在序列中。 You are in fact never even using or considering the 7 you input. 事实上你甚至从未使用或考虑过你输入的7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM