【问题标题】:Same code yields different result when printing index of a list打印列表索引时,相同的代码会产生不同的结果
【发布时间】:2021-12-28 20:37:46
【问题描述】:
master = [[2,3],[5,1,3]]
mySection = 2

availableList = []
for entry in master[mySection-1]:
    if entry != 0:
        availableList.append(master[mySection-1].index(entry))
        print(master[mySection-1].index(entry))

这段代码完美地打印了指定子列表的索引,因为它打印了 0、1、2

master = [[2,3],[0,0,3]]
mySection = 2

inUseList = []
for entry in master[mySection-1]:
    if entry == 0:
        inUseList.append(master[mySection-1].index(entry))
        print(master[mySection-1].index(entry))

此代码应该像其他代码一样打印指定子列表的索引。我在这里唯一更改的是 if 条件和包含零的主列表,但它会打印 0, 0 这不是索引

起初我认为这是一个逻辑错误,因为我正在创建一个更大的项目,但我分别测试了它们,甚至重写了它们并得到了相同的结果。如何让第二组代码打印索引而不是索引内的元素?

【问题讨论】:

  • index 返回第一个匹配项的索引。
  • 你真正想要达到什么目的?

标签: python loops indexing nested-lists


【解决方案1】:

.index() 返回给定元素的 first 实例的索引。由于0 出现在索引 0 和 1 中,调用 .index(0) 返回 0。

您正在寻找的是打印给定元素的实际索引,而不是 .index() 的返回值。这可以使用enumerate()

for index, entry in enumerate(master[mySection-1]):
    if entry == 0:
        inUseList.append(index)
        print(index)

【讨论】:

  • 我从来没有使用过这种程度的索引。我真的很感激这种洞察力。我已将两者都更改为使用 enumerate()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多