此程序必须从项目列表中输出笔画。
例如:
输入->牛、苹果、猪、牛
产量--> 3头牛、1只苹果和1头猪
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‘(所以我不需要写’和‘在末尾)。该怎么做呢?
发布于 2020-12-22 20:52:40
你想要这个吗?
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()]))输出:
3 cows and 1 apple and 1 pig发布于 2020-12-22 20:56:01
不要在循环中进行连接。将每个项目放在一个列表中,然后使用join()组合它们。
您还可以使用items()方法提取动物名称并将其直接计数到变量中。
words = []
for animal, count in a.items()
if count > 1:
animal += "s"
words.append(f"{count} {animal}"
return " and ".join(words)发布于 2020-12-22 21:03:40
假设Barmar和baduker的响应显示了一种更好的方法,想要使用您的代码,如果输入是一个带有逗号分隔的单词列表的字符串,则需要做的是由","拆分字符串。
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]以及:
print(count_things("cow, apple, pig, cow, cow"))现在应该返回:
1 cow and 1 apple and 1 pig and 2 cows https://stackoverflow.com/questions/65415626
复制相似问题