我有一个奇怪的问题。我正在尝试创建一个引用生成器,它有一个引用部分的字典(每个值都是一个列表),从该列表中为每个键提取一个随机项目并将其附加到另一个列表中。然后将打印该列表以显示最终报价。
但是,我以随机顺序获取报价的部分。运行时,我得到这样的信息:
['avoid ', 'hobby.', "it's easy to ", 'your ', 'Occasionally ', 'most important ']
这是我的代码:
from random import choice
quoteWords = {
"one": ["Sometimes ", "Often ", "Occasionally ", "Usually "],
"two": ["it's best to ", "you should ", "you shouldn't ", "it's easy to ", "it's hard to "],
"three": ["do ", "avoid ", "finish", "create ", "witness "],
"four": ["the ", "a ", "your ", "society's ", "your friends' ", "the government's "],
"five": ["best ", "most important ", "funniest "],
"six": ["work.", "art.", "hobby.", "posessions."],
}
def inspire():
quote = []
counter = 0
for key in quoteWords:
quote.insert(counter, choice(quoteWords[key]))
counter += 1
return(quote)
print(inspire())
任何帮助将不胜感激。提前致谢!
您可以使用OrderedDict
! 通常dict
,不能保证keys
' 或items
' 顺序:
from collections import OrderedDict
quoteWords = OrderedDict([
("one", ["Sometimes ", "Often ", "Occasionally ", "Usually "]),
("two", ["it's best to ", "you should ", "you shouldn't ", "it's easy to ", "it's hard to "]),
("three", ["do ", "avoid ", "finish", "create ", "witness "]),
("four", ["the ", "a ", "your ", "society's ", "your friends' ", "the government's "]),
("five", ["best ", "most important ", "funniest "]),
("six", ["work.", "art.", "hobby.", "posessions."]),
])
# ...
print(''.join(inspire()))
Usually you should witness the best work.
您使用它的方式,您甚至不需要映射。您可以只使用列表列表并从每个列表中选择一个项目。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句