繁体   English   中英

列表中的格式化字符串

[英]Formatted string in list

它的解决方案或其他方式是什么? 我写了一个字符串列表,如前所示,我想对其进行格式化并包含选项,然后我想打印(通过从用户那里获取输入)它的索引,但是在终端上抛出了错误,即列表中不存在 0 或 1 索引。

options = ["a) 31\n b) 32\n c) 33\n d)34", "a) Energy\n b) Motion\n c) Motion and Energy\n d)Nothing"]
questions = [f"Our brain is consists of ..... bones:\n{options.index(1)}",
              f"Physics is the study of .......\n{options.index(2)}"]

q_1 = input(questions[0])

options.index(1)在列表中搜索1并返回其索引。 这似乎不是你想要的。

您似乎想获得options的第一个元素,它是用options[0]来完成的。

它是0而不是1 ,因为 Python 列表是从0开始索引的,而不是1

当您索引questions时,您这样做是正确的。

我已经用 options[1] insted of options.index(1) 更正了你的代码

options = ["a) 31\n b) 32\n c) 33\n d)34", "a) Energy\n b) Motion\n c) Motion and Energy\n d)Nothing"]
questions = [f"Our brain is consists of ..... bones:\n{options[0]}", f"Physics is the study of .......\n{options[1]}"]

q_1 = input(questions[0])

index 方法搜索您提供的值是否在列表中,即它 options.index(0) 检查是否存在值为 0 的元素并返回其索引

要获取索引 0 处的元素,请使用 list[0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM