gpt4 book ai didi

python - 将元组列表混合并迭代到文本模板中

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:59 25 4
gpt4 key购买 nike

我得到了一个列表和一个元组列表,每个都包含字符串:

names = ['joseph', 'parker', 'john']
interests = [('apples', 'design'),('bananas','economy'),('pears','medicine')]

text_template = 'hi my name is {name}, i like {interests}, im studying {interests} everytime / '

我正在努力实现这一目标:

hi my name is joseph, i like apples, im studying design everytime / 
hi my name is joseph, i like bananas, im studying economy everytime /
hi my name is joseph, i like pears, im studying medicine everytime


hi my name is parker, i like apples, im studying design everytime /
hi my name is parker, i like bananas, im studying economy everytime /
hi my name is parker, i like pears, im studying medicine everytime

hi my name is john, i like apples, im studying design everytime /
hi my name is john, i like bananas, im studying economy everytime /
hi my name is john, i like pears, im studying medicine everytime

谢谢大家!!

最佳答案

我建议对您的模板稍作更改,这样字段名称就不会重复。

text_template = 'hi my name is {name}, i like {interest}, im studying {degree} everytime / '

现在您可以:

>>> from itertools import product
>>> for name, (interest, degree) in product(names, interests):
...: print(text_template.format(name=name, interest=interest, degree=degree))
...:
hi my name is joseph, i like apples, im studying design everytime /
hi my name is joseph, i like bananas, im studying economy everytime /
hi my name is joseph, i like pears, im studying medicine everytime /
hi my name is parker, i like apples, im studying design everytime /
hi my name is parker, i like bananas, im studying economy everytime /
hi my name is parker, i like pears, im studying medicine everytime /
hi my name is john, i like apples, im studying design everytime /
hi my name is john, i like bananas, im studying economy everytime /
hi my name is john, i like pears, im studying medicine everytime /

...如果空行很重要:

>>> for i, (name, (interest, degree)) in enumerate(product(names, interests), 1):
...: print(text_template.format(name=name, interest=interest, degree=degree))
...: if not i%len(names):
...: print()
...:
hi my name is joseph, i like apples, im studying design everytime /
hi my name is joseph, i like bananas, im studying economy everytime /
hi my name is joseph, i like pears, im studying medicine everytime /

hi my name is parker, i like apples, im studying design everytime /
hi my name is parker, i like bananas, im studying economy everytime /
hi my name is parker, i like pears, im studying medicine everytime /

hi my name is john, i like apples, im studying design everytime /
hi my name is john, i like bananas, im studying economy everytime /
hi my name is john, i like pears, im studying medicine everytime /

关于python - 将元组列表混合并迭代到文本模板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53308464/

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