【问题标题】:Nested lists python嵌套列表python
【发布时间】:2011-11-18 21:08:43
【问题描述】:

谁能告诉我如何调用嵌套列表中的索引?

一般我只写:

for i in range (list)

但是如果我有一个嵌套列表如下:

Nlist = [[2,2,2],[3,3,3],[4,4,4]...]

我想分别浏览每个索引?

【问题讨论】:

  • 你需要重写你的问题并说清楚。您对“索引”的使用是可疑的;也许你的意思是“项目”?
  • 这是一个关于遍历嵌套列表的问题,other 是关于比较嵌套列表的。

标签: python


【解决方案1】:

如果您真的需要索引,您可以对内部列表再次执行您所说的操作:

l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
    for index2 in xrange(len(l[index1])):
        print index1, index2, l[index1][index2]

但是遍历列表本身更加pythonic:

for inner_l in l:
    for item in inner_l:
        print item

如果你真的需要索引你也可以使用enumerate:

for index1, inner_l in enumerate(l):
    for index2, item in enumerate(inner_l):
        print index1, index2, item, l[index1][index2]

【讨论】:

  • 这很有帮助,但我讨厌你如何使用变量“l”、i 和 1。太难阅读和区分我不知道人们为什么要为他们的示例这样做。
【解决方案2】:

试试这个设置:

a = [["a","b","c",],["d","e"],["f","g","h"]]

要打印第一个列表 ("b") 中的第二个元素,请使用 print a[0][1] - 对于第三个列表 ("g") 中的第二个元素:print a[2][1]

第一个括号引用您正在访问的嵌套列表,第二对引用该列表中的项目。

【讨论】:

    【解决方案3】:

    你可以这样做。适应你的情况:

      for l in Nlist:
          for item in l:
            print item
    

    【讨论】:

      【解决方案4】:

      问题标题太宽,作者的需求更具体。就我而言,我需要从嵌套列表中提取所有元素,如下例所示

      示例:

      input -> [1,2,[3,4]]
      output -> [1,2,3,4]
      

      下面的代码给了我结果,但我想知道是否有人可以创建一个更简单的答案:

      def get_elements_from_nested_list(l, new_l):
          if l is not None:
              e = l[0]
              if isinstance(e, list):
                  get_elements_from_nested_list(e, new_l)
              else:
                  new_l.append(e)
              if len(l) > 1:
                  return get_elements_from_nested_list(l[1:], new_l)
              else:
                  return new_l
      

      方法的调用

      l = [1,2,[3,4]]
      new_l = []
      
      get_elements_from_nested_list(l, new_l)
      

      【讨论】:

        【解决方案5】:
        n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
        def flatten(lists):
          results = []
          for numbers in lists:
            for numbers2 in numbers:
                results.append(numbers2) 
          return results
        print flatten(n)
        

        输出:n = [1,2,3,4,5,6,7,8,9]

        【讨论】:

        【解决方案6】:

        我认为您想同时和分别访问列表值及其索引:

        l = [[2,2,2],[3,3,3],[4,4,4],[5,5,5]]
        l_len = len(l)
        l_item_len = len(l[0])
        for i in range(l_len):
            for j in range(l_item_len):
                print(f'List[{i}][{j}] : {l[i][j]}'  )
        

        【讨论】:

          猜你喜欢
          • 2019-03-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-20
          • 1970-01-01
          • 1970-01-01
          • 2018-06-02
          相关资源
          最近更新 更多