首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除最后5个符号

删除最后5个符号
EN

Stack Overflow用户
提问于 2020-12-22 20:47:31
回答 4查看 59关注 0票数 0

此程序必须从项目列表中输出笔画。

例如:

输入->牛、苹果、猪、牛

产量--> 3头牛、1只苹果和1头猪

代码语言:javascript
复制
def count_things(text):
    a = {}
    for i in text:
        if i in a:
            a[i] += 1
        else:
            a[i] = 1

    text = ''

    for i in a:
        if a[i] > 1:
            text += str(a[i]) + ' ' + str(i) + 's and '
        else:
            text += str(a[i]) + ' ' + str(i) + ' and '

    return text[:-5]

我想输出行,而不使用最后一行的':-5‘(所以我不需要写’和‘在末尾)。该怎么做呢?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-12-22 20:52:40

你想要这个吗?

代码语言:javascript
复制
from collections import Counter

stuff = ["cow", "apple", "pig", "cow", "cow"]
print(" and ".join([f"{v} {k + 's' if v > 1 else k}" for k, v in Counter(stuff).items()]))

输出:

代码语言:javascript
复制
3 cows and 1 apple and 1 pig
票数 3
EN

Stack Overflow用户

发布于 2020-12-22 20:56:01

不要在循环中进行连接。将每个项目放在一个列表中,然后使用join()组合它们。

您还可以使用items()方法提取动物名称并将其直接计数到变量中。

代码语言:javascript
复制
words = []
for animal, count in a.items()
    if count > 1:
        animal += "s"
    words.append(f"{count} {animal}"
return " and ".join(words)
票数 1
EN

Stack Overflow用户

发布于 2020-12-22 21:03:40

假设Barmarbaduker的响应显示了一种更好的方法,想要使用您的代码,如果输入是一个带有逗号分隔的单词列表的字符串,则需要做的是由","拆分字符串。

代码语言:javascript
复制
def count_things(text):
    a = {}
    for i in text.split(","):
        if i in a:
            a[i] += 1
        else:
            a[i] = 1

    text = ''

    for i in a:
        if a[i] > 1:
            text += str(a[i]) + ' ' + str(i) + 's and '
        else:
            text += str(a[i]) + ' ' + str(i) + ' and '

    return text[:-4]

以及:

代码语言:javascript
复制
print(count_things("cow, apple, pig, cow, cow"))

现在应该返回:

代码语言:javascript
复制
1 cow and 1  apple and 1  pig and 2  cows 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65415626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档