【问题标题】:list search obj with index number使用索引号列出搜索 obj
【发布时间】:2016-09-13 11:33:38
【问题描述】:
stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam Sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', '’s-Hertogenbosch', 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht']

我试过了:

print(sations.index[1])

我在搜索索引时找不到打印列表项的方法。

【问题讨论】:

  • list.index 是一个函数,因此尝试下标是行不通的。如果您要打印列表中的项目,请使用stations[0] 或通常使用stations[n] 索引列表,其中n[0, len(stations-1)] 中。如果您想获取某个项目的索引,请使用stations.index('item-name')
  • 对不起,问题不清楚。你能解释一下(在问题中)你想做什么吗?
  • 您打印的是sations.index[1],而不是stations.index[1]
  • 谢谢它的工作我使用了站[x]格式

标签: python list python-3.x


【解决方案1】:

如果要查找对象,可以使用index()。例如

index = 0
if "Zaandam" in stations:
    index = stations.index("Zaandam")
print(stations[index])

Zaandam 的索引被记录到变量index,然后它的记录索引被用于print 本身。 if 语句只是一个包装器。

【讨论】:

    猜你喜欢
    • 2015-02-07
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    相关资源
    最近更新 更多