我制作了一个赠品模块,现在我正在尝试创建一个函数,该函数使用两个这样的列表为所有获奖者返回一个祝贺字符串。
winners = ["john", "anna", "max", "george"]
prizes = [(1, "apple"), (1, "pear"), (2, "carrots")]
# (number of these prize avaible, the prize)
它们的长度不必与您看到的长度相同,但是奖品中的数字总和始终与获胜者中的长度相同。
我理想的字符串应该是这样的。
"Congratulations to john for winning 1 apple, anna for winning 1 pear, and max and george for winning 1 carrot each."
我知道我可能可以扩大奖项清单并在以后压缩两个奖项。但我实际上是在尝试将拥有多个获奖者的奖项分组归纳。 100个奖项和总和(x个奖项中x的x [0])。
这是我到目前为止一直在尝试的方法,但是当每个奖项的获奖者超过两个时,它并没有真正的用处,而且我真的不知道一种方法来知道我何时在上次迭代中替换,与和。
winners = ["john", "anna", "max", "george"]
prizes = [(2, "peanuts"), (2, "carrot")]
def congratulations(winners, prizes):
s = "Congratulations to "
for w in winners:
for p in prizes:
s += "{} for winning {} {}, ".format(w, p[0], p[1])
break
return s
print(congratulations(winners, prizes))
#Congratulations to john for winning 2 peanuts, anna for winning 2 peanuts, max for winning 2 peanuts, george for winning 2 peanuts,
有些事情我不在乎,例如奖品写成复数形式,或者您需要在末尾添加。感谢您的帮助。
感谢亨利,我做了一些小的修改,但是代码是相同的。
winners = ["john", "anna", "max", "george", "carlos"]
prizes = [(1, "apple"), (3, "pears"), (1, "carrots")]
def congratulations(winners, prizes):
s = "Congratulations to "
i = 0
for p in prizes:
w = ", ".join(winners[i : i + p[0]])
w = " and ".join(w.rsplit(", ", 1))
s += "{} for winning {} {}{}; ".format(w, 1, p[1], "" if p[0] == 1 else " each")
i += p[0]
s = s[:-2] + "."
k = s.rfind(";")
s = s[:k] + "; and" + s[k + 1 :]
return s
w = congratulations(winners, prizes)
print(w)
# Congratulations to john for winning 1 apple, anna, max and george for winning 1 pears each, and carlos for winning 1 carrots.
答案 0 :(得分:2)
最好先遍历奖品列表,然后将优胜者放在字符串结构中,例如:
winners = ["john", "anna", "max", "george"]
prizes = [(2, "peanuts"), (2, "carrot")]
def congratulations(winners, prizes):
s = "Congratulations to "
i = 0
for p in prizes:
w = ', '.join(winners[i: i + p[0]])
s += "{} for winning {} {}{}, ".format(w, 1, p[1], '' if p[0]==1 else " each")
i += p[0]
return s
print(congratulations(winners, prizes))
# Congratulations to john, anna for winning 1 peanuts each, max, george for winning 1 carrot each,
在首选使用w
而不是and
的情况下,您需要修改,
的用语,例如:
w = ', '.join(winners[i: i + p[0]])
w = ' and '.join(w.rsplit(', ', 1))
它将用', '
代替最后一次出现的' and '
,最后一个字符串看起来像
Congratulations to john and anna for winning 1 peanuts each, max and george for winning 1 carrot each,
答案 1 :(得分:1)
请尝试以下操作:
vec.reserve(2);