【问题标题】:Add up numbers - that can be printed - in Python将数字相加 - 可以打印 - 在 Python 中
【发布时间】:2019-12-10 06:04:24
【问题描述】:

我正在为一个看似简单的案例而苦苦挣扎。 我已经到了可以搜索特定输入的地步,我让程序打印给定输入在列表的每个元素中出现的次数。

以下面的列表为例:

title = ['hello 2017', 'hello 2019', 'bye 2017']

我的(非常简单的)代码:

for s in title:
    count = s.count('2017')
    print(count)

输出:

1
0
1

我尝试将 print(count) 替换为以下内容:

    if count == 1:
        total =+ 1

print(total)

打印时只给出“1”。

我觉得问这个问题有点傻,但如果有人能给点提示就好了。

【问题讨论】:

  • += 就是你要找的东西

标签: python list count


【解决方案1】:

您可以尝试以下方法吗:

title = ['hello 2017', 'hello 2019', 'bye 2017']
total = 0
for s in title:
    count = s.count('2017')
    total += count
    print(total)

输出:

1
1
2

title = ['hello 2017', 'hello 2019', 'bye 2017']
total = 0
for s in title:
    count = s.count('2017')
    if count >= 1:
        total += count
        print(total)
    else:
        print(0)

输出:

1
0
2

【讨论】:

  • 啊,我明白了.. 让我们忘记这个问题.. 还是谢谢。
【解决方案2】:
title = [ hello 2017, hello 2019, bye 2017 ]
for s in title:
    count = s.count('2017')
    print(count)

如果我正确理解您的问题,是的,您需要理解这一点

i+=1i=i+1 相同,而 i=+1 仅表示i=(+1)

The difference between '+=' and '=+'?

所以你必须将你的代码重写为:

title = ['hello 2017', 'hello 2019', 'bye 2017']
total = 0
for s in title:
    count = s.count('2017')
    if count == 1:
        total += count
    else:
        print("Count not equals to 1")
print(total)

【讨论】:

    【解决方案3】:

    我可能完全误解了你的问题,但它是这样的:

    import re
    
    title = ['hello 2017', 'hello 2019', 'bye 2017']
    
    for item in title:
        numbers = re.findall(r"(\d)", item)
        total = 0
        for num in numbers:
            try:
                total += int(num)
            except:
                pass
        print(total)
    

    输出:

    10
    12
    10
    

    把每一年的数字加起来

    【讨论】:

      【解决方案4】:

      您可以将出现次数统计到一个列表中并在其上使用sum() 来获取总数

      title = ['hello 2017', 'hello 2019', 'bye 2017']
      occurrences = [s.count('2017') for s in title]
      print(*occurrences) # 1 0 1, add sep='\n' to print vertically
      print(sum(occurrences)) # 2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多