按顺序附加到 for 循环中的字典列表(Python 3)

用户7450368

我有一个奇怪的问题。我正在尝试创建一个引用生成器,它有一个引用部分的字典(每个值都是一个列表),从该列表中为每个键提取一个随机项目并将其附加到另一个列表中。然后将打印该列表以显示最终报价。

但是,我以随机顺序获取报价的部分。运行时,我得到这样的信息:

['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())

任何帮助将不胜感激。提前致谢!

schwobaseggl

您可以使用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

附加到Python字典中的列表

在for循环中将值附加到字典中,python

在python中按顺序将多个字典附加到一个字典中

如何使用python 3附加到文件

Python:同时在for循环中添加到列表列表

如何在for循环中将列表正确附加到DataFrame

如何在python的for循环中将不同的字典添加到同一列表中?

在for循环中附加到空数组(python)

Python循环字典按分配顺序

附加到Python中的嵌套列表或字典

通过循环附加 Python 字典列表

Python:在for循环中附加到字典

append 和 enumerate 的行为 - 当附加到列表时,我可以按与附加方式不同的顺序返回值吗?

将结果附加到列表或数组 python3

通过python 3.x中的字典循环列表

Python 3:使用 if else 进行字典理解并附加到列表中

如何将for循环中的字典附加到列表中(具体示例)

创建列表列表并添加到 for 循环中的字典

根据条件 python3 将变量附加到列表

按顺序附加到嵌套列表中的列表元素字典

如何在循环中将数据附加到列表中?

Python 3:使用 while True 循环在列表上附加整数

如果 else 语句附加到 for 循环中的列表

Python 3 dict 在字典列表中按值排序?

如何在循环中将新元素附加到 3D numpy 数组中?

附加到 Python 全局字典列表

在python的for循环中将许多列表添加到嵌套字典中

在循环中创建不同长度的字典以附加到列表中。(json 到 Pandas 数据框)

在公式的while循环中按顺序附加