【问题标题】:Nested list looping and wanting to make each loop have index 0 and 1嵌套列表循环并希望使每个循环具有索引 0 和 1
【发布时间】:2020-02-28 21:09:55
【问题描述】:

列表

list_a = [[1, 2],[3, 4], [5, 6]]

for index, item in enumerate(list_a):
# do something 

所需任务说明

我的问题是,如果我想检索 list_a 中的每个单独列表作为索引 0 和 1,我将如何编写此循环。目前 [1, 2] 是索引 0,[3, 4] 是索引 1 等等.但是我要追的是以下内容:

[1, 2] 将 1 作为索引 0,将 2 作为索引 1,然后我将执行一些任务,然后转到以下内容,其中 [3, 4] 将 3 作为索引 0,将 4 作为索引 1 和执行与以前相同的任务。任何帮助都是极好的! :)

【问题讨论】:

  • 如果我理解正确,您已经拥有所需的索引。试试print(list_a[0][0]), list_a[0][1]))。只需在已有的循环中通过 item 嵌套另一个循环
  • 你已经在循环内的变量item中得到了你需要的东西(如果我理解你的话)
  • 为什么需要索引 - 大多数情况下,这些值更重要...您可以通过 for item in listvar: 处理它们

标签: python loops nested-loops enumerate


【解决方案1】:
for small_list in list_a:
    for index, item in enumerate(small_list):
        print index, item

【讨论】:

  • @MadPhysicist 我不确定你的意思。这将 1 作为索引 0,2 作为索引 1,3 作为索引 0,4 作为索引 1,正如操作所要求的那样
  • 我原来的评论很愚蠢。我没有仔细阅读。我很抱歉。
【解决方案2】:

你不需要这个枚举:

list_a = [[1, 2],[3, 4], [5, 6]]

for item in list_a:
    print(item[0], item[1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2021-11-24
    • 1970-01-01
    • 2020-04-16
    • 2019-04-22
    • 2018-01-06
    • 2014-01-16
    相关资源
    最近更新 更多