首页 > 解决方案 > 如何通过不同长度的列表生成随机句子?

问题描述

我正在为我的男朋友制作周年纪念礼物,我想向他发送一个程序,让他每次运行时都会有不同的理由让我爱他(他学习计算机科学,这很合适)。

经过研究,我知道我希望它在我说打印后这样做:“我爱 [昵称] 的原因:[我爱他的原因]

将有 6 个昵称和 100 个理由,我希望它每次运行时都返回一句话!

我感谢任何帮助<3

标签: pythonlist

解决方案


我老婆+酒=

import random

nicknames = [
    'Panda Bear',
    'My Love Love',
    'White Chocolate'
]

reasons = [
    'the way you look at me',
    'your eyes',
    'your kisses',
    'your cheesy jokes',
    'your soft pinkish lips',
    'your ear lobes'
]

def get_message(name_list, reason_list):
    name = random.choice(name_list)
    reason = random.choice(reason_list)
    return f'Reason why I love {name}: {reason}.'

# print one random reason
print(get_message(nicknames, reasons))

# print ten random reasons for fun
for n in range(10):
    print(get_message(nicknames, reasons))

输出:

Reason why I love Panda Bear: your cheesy jokes.
Reason why I love Panda Bear: your kisses.
Reason why I love My Love Love: your soft pinkish lips.
Reason why I love My Love Love: the way you look at me.
Reason why I love White Chocolate: your cheesy jokes.
Reason why I love White Chocolate: the way you look at me.
Reason why I love My Love Love: the way you look at me.
Reason why I love White Chocolate: your kisses.
Reason why I love White Chocolate: your soft pinkish lips.
Reason why I love My Love Love: your soft pinkish lips.
Reason why I love Panda Bear: your ear lobes.

您可以添加自己的原因和昵称,用逗号分隔并用引号括起来。


推荐阅读