【问题标题】:Python: Trouble sub scripting lists and accessing data in later print statement, what am I doing wrong?Python:在稍后的打印语句中子脚本列表和访问数据时遇到问题,我做错了什么?
【发布时间】:2018-02-22 09:36:30
【问题描述】:

这是我的任务,我对 Python 还很陌生,所以我有点挣扎enter image description here

(我只需要做8匹马)

这是我目前的代码:

horse_info = [['A',11,12],['B',17,7],['C',14,28],['D',15,10],['E',18,30],['F',13,3],['G',16,18],['H',12,23]]

max_h = int(input('Maximum height: '))
max_a = int(input('Maximum age: '))

for i in range(len(horse_info)):
    if int(max_h) <= horse_info[i[i]] and int(max_a) <= horse_info[i[i]]:
        print('yes')

但我收到此错误:

> Traceback (most recent call last):   File
> "/Users/MattDaGama/Documents/Q43.py", line 7, in <module>
>     if int(max_h) <= horse_info[i[i]] and int(max_a) <= horse_info[i[i]]: TypeError: 'int' object is not subscriptable

希望有任何帮助:)

编辑:

我想我已经弄清楚了 if 语句,但我不确定如何制作 print 语句。

horse_info = [['A',11,12],['B',17,7],['C',14,28],['D',15,10],['E',18,30],['F',13,3],['G',16,18],['H',12,23]]

max_h = int(input('Maximum height: '))
max_a = int(input('Maximum age: '))

for i in range(len(horse_info)
    if int(max_h) <= horse_info[i][1] and int(max_a) <= horse_info[i][2]:
        print(horse_info[i][1,2,3])

当我尝试运行代码时,它不会打印任何内容。

【问题讨论】:

  • i 是一个整数......所以i[i] 没有意义......你可能只是说horse_info[i] - 尽管你不需要在Python中通过索引来访问东西.. . 你可以直接循环它们。
  • 可能是horse_info[i][1]horse_info[i][2]
  • 我希望它进入每个子列表并比较它们
  • @Matthew Valetsky。该问题已在下面提出并回答。下面的答案都回答了你的第一个和第二个问题。我很高兴根据您的要求进行编辑

标签: python


【解决方案1】:

问题是当你遍历一个范围时,i 是一个整数。整数数据类型不可下标(即,您不能对 list[i] 执行相同的操作,例如跳转到列表的索引。整数没有索引。

所以作为一个起点:

if int(max_h) &lt;= horse_info[i[i]] and int(max_a) &lt;= horse_info[i[i]]:

应该是-

if int(max_h) &lt;= horse_info[i][1] and int(max_a) &lt;= horse_info[i][2]:

假设horse_info[0][1] = 11horse_info[0][2] = 12 基于问题中的变量声明,(即horse_info = [['A',11,12], ... ]

您有一个列表列表,i 是您要使用的外部列表的索引,第二组 [] 是您要使用的值的索引

【讨论】:

  • 我将如何开发打印语句
  • 好吧,您没有打印任何内容,因为 if 条件永远不会为真。我不知道你的输入值是什么。但请确保您确实有一个能够满足条件的 horse_info。也就是说print(horse_info[i][1,2,3]) 会出错。如果要打印该列表索引的所有数据,只需执行print(horse_info[i]) 将输出['A',11,12]print(horse_info[i][0], horse_info[i][1], horse_info[i][2]) 将输出A 11 12
  • 仅供参考,我在测试中使用了 14 和 14 以及上面的编辑打印,它运行良好 :) 如果可行,请接受作为答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多