我创建了一个程序,该程序从与主题相关联的文本文档中导入的列表中选择随机项目。饮食中的食物包含比萨饼,面食和汉堡。但是,当打印出结果时,所选项目将带有括号,方括号和语音标记。我将如何删除它们?
things_to_do=[
("eat", [(foods[randint(0,20)])]),
("do", [(sports[randint(0,60)])]),
("drink a",[(coffees[randint(0,20)])])]
print "Whilst in town you decided to " + str(things_to_do[randint(0,2)])]
最佳答案
这些括号,引号等只是更复杂的数据结构(例如string representation或lists
)的tuples
的一部分。您需要正确准备/格式化数据以获得更好的输出:
things_to_do = [
("eat", foods[randint(0,20)]), # less complex than the singleton lists in your code
("do", sports[randint(0,60)]),
("drink a", coffees[randint(0,20)])
]
verb, obj = things_to_do[randint(0,2)]
print "Whilst in town you decided to {v} {o}".format(v=verb, o=obj)
String formatting in the docs。
关于python - Python嵌套列表删除括号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41683111/