从多个列表中生成随机条目的Python代码
我是Python新手,正在尝试编写一个代码,通过从列表中选择一个随机条目来生成一个故事的核心元素[主题] [特征] [主题] [地点]和[线路]。我写的代码如下。从多个列表中生成随机条目的Python代码
我有2个问题:
1)目前的代码会允许我创建每个列表中的新条目,但是当我关闭Python和重新启动程序,我创建都不见了条目。我怎样才能使新条目永久存储在列表中?我需要某种数据库吗?
2)6. Storybox的代码 - 我希望程序做的主要事情! - 不管用。任何关于如何让Python打印每个列表中随机选择的条目的建议?
在此先感谢您的帮助。
#Storybox program
#Generates a random selection of my story ideas
characters = []
traits = []
locations = []
themes = []
lines = []
choice = None
while choice != "0":
print(
"""
Storybox:
0 - Exit
1 - Add character
2 - Add trait
3 - Add location
4 - Add theme
5 - Add line
6 - Generate Story
7 - View all entries
"""
)
choice = input("Choice: ")
print()
#exit
if choice == "0":
print("Goodbye")
#add a character
elif choice == "1":
character = input("Enter character: ")
characters.append(character)
#add a trait
elif choice == "2":
trait = input("Enter character trait: ")
traits.append(trait)
#add a location
elif choice == "3":
location = input("Enter location: ")
locations.append(location)
#add a theme
elif choice == "4":
theme = input("Enter theme: ")
themes.append(theme)
#add good lines
elif choice == "5":
line = input("Enter good line: ")
lines.append(line)
#Generate storybox
elif choice == "6":
print("Your storybox is....")
storyboxcharacter = random.choice(characters)
print(storyboxcharacter)
storyboxtrait = random.choice(traits)
print(storyboxtrait)
storyboxtheme = random.choice(themes)
print(storyboxtheme)
storyboxlocation = random.choice(locations)
print(storyboxlocation)
storyboxline = random.choice(lines)
print(storyboxline)
#Display all entries so far
elif choice == "7":
print("Characters:")
for character in characters:
print(character)
print("Traits:")
for trait in traits:
print(trait)
print("Themes:")
for theme in themes:
print(theme)
print("Locations:")
for location in locations:
print(location)
print("Good lines:")
for line in lines:
print(line)
input("\n\nPress the enter key to exit.")
1)是的,您需要以某种方式将数据存储在文本文件或数据库中。数据库在这一点上是过分的,所以我建议像json这样的东西。
2)删除randint解决 - random.choice是肯定更好
他已经是random.choice,比使用randint的手动方法好得多。 – nemo 2013-03-02 20:22:43
啊,我没有向下滚动查看他的其他代码。我之前没有见过random.choice,谢谢。 – Matt 2013-03-02 20:26:09
感谢您的回答,json看起来很有用(尽管需要我花些时间来研究如何使用它)。 @tcaswell:问题是,当我输入6时出现错误消息:选择:6 您的故事框是...... 回溯(最近呼叫最后): 文件“C:\ Python31 \ Storybox”,行69,
1)是的,你需要某种形式的持久性存储。一个数据库可以工作,就像一个写入平面文件(csv或pickle等)的方案一样。 2)什么是不适用的? – tacaswell 2013-03-02 20:19:33