PyCharm中Python测验程序嵌套列表创建失败及报错解决求助
解决Python嵌套列表创建错误的方法
你的代码里options嵌套列表的问题很明确:子列表之间缺少逗号分隔。Python会把后续的子列表当成前一个子列表的索引去访问,但前一个子列表的元素是字符串,字符串仅支持整数索引或切片,无法用列表作为索引,因此触发了类型错误。
修正后的基础代码
只需在每个子列表之间添加逗号即可:
question = ["1. Grand Central Terminal, Park Avenue, New York is the world's", "2. Entomology is the science that studies", "3. Eritrea, which became the 182nd member of the UN in 1993, is in the continent of"] options = [ ["A. Largest railway station B. Highest railway station" "C. Longest railway station D. None of the above"], ["A. Behavior of human beings B. Insects" "C. The origin and history of technical and scientific terms D. The formation of rocks"], ["A. Asia B. Africa" "C. Europe D. Australia"] ]
更实用的优化写法
如果后续需要对单个选项做逻辑处理(比如判断用户输入),建议把每个选项拆分为独立的字符串元素,这样代码逻辑会更清晰:
question = ["1. Grand Central Terminal, Park Avenue, New York is the world's", "2. Entomology is the science that studies", "3. Eritrea, which became the 182nd member of the UN in 1993, is in the continent of"] options = [ ["A. Largest railway station", "B. Highest railway station", "C. Longest railway station", "D. None of the above"], ["A. Behavior of human beings", "B. Insects", "C. The origin and history of technical and scientific terms", "D. The formation of rocks"], ["A. Asia", "B. Africa", "C. Europe", "D. Australia"] ]
内容的提问来源于stack exchange,提问作者IRON MAN
相关产品推荐
相关产品推荐

