gpt4 book ai didi

python - 从两个列表创建自定义字符串

转载 作者:太空宇宙 更新时间:2023-11-04 11:10:20 24 4
gpt4 key购买 nike

我做了一个赠品模块,现在我正在尝试创建一个函数,它使用两个像这样的列表为所有获奖者返回祝贺字符串。

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[0] for x in prizes)获奖者。

这是我到目前为止尝试过的方法,但是当每个奖项有两个以上的获奖者时,它并不是很有用,而且我真的不知道有什么方法可以知道我在最后一次迭代中何时替换 ,用一个和。

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,

不过有些事情我不在乎,比如奖品是否写成复数,或者您需要在末尾添加 , 。感谢您的帮助。

感谢 Henry,我做了一些小修改,但代码是一样的。

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.

最佳答案

最好先循环奖品列表,然后将获奖者放在字符串构造中,例如:

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,

如果首选 and 而不是 ,,则需要修改 w pharse,例如:

w = ', '.join(winners[i: i + p[0]])
w = ' and '.join(w.rsplit(', ', 1))

它将用 ' 和 ' 替换最后一次出现的 '、',最终的字符串看起来像恭喜john和anna各赢得1个花生,max和george各赢得1个胡萝卜,

关于python - 从两个列表创建自定义字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58427751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com