如何返回嵌套的列表元素并在python中按顺序使用它们?

时间:2015-12-27 19:17:21

标签: python list function

def main_func():
   chunk= [["ABABA","ACA"],["AGAGA","AAVA"],["XBX","ARAA"],["AADA","AAA"],["BABAB","ABA"]]
   for a in chunk:
      return a

我想调用每个函数调用的块列表中的每个列表..

   def call_list():

   ....
   ....
   .... 

   a=main_func()
   call_list()

但是我只获得一个["ABABA","ACA"]列表。

如何调用块列表中的每个列表?

2 个答案:

答案 0 :(得分:0)

让我们说你有一个变量:

a = [1, 1, 1, 1, 1, 1,[1, 1, 1, 1, 2,[1, 1, 1, 3,4]]] The code above will still give you the last element.

>>> a = [1, 1, 1, 1, 1, 1,[1, 1, 1, 1, 2,[1, 1, 1, 3,4]]]
>>> a[-1]
[1, 1, 1, 1, 2, [1, 1, 1, 3, 4]]
>>> a[-1][-1]
[1, 1, 1, 3, 4]
>>> a[-1][-1][-1]
4

希望这有帮助!

答案 1 :(得分:0)

将您的功能变为发电机:

def gen_chunks():
    chunks = [["ABABA","ACA"],["AGAGA","AAVA"],["XBX","ARAA"],
              ["AADA","AAA"],["BABAB","ABA"]]
    for chunk in chunks:
        yield chunk

并使用next()而不是调用函数:

>>> chunks = gen_chunks()
>>> next(chunks)
['ABABA', 'ACA']
>>> (chunks)
['AGAGA', 'AAVA']