【问题标题】:How to return nested list elements and use them in order in python?如何返回嵌套列表元素并在python中按顺序使用它们?
【发布时间】:2015-12-27 19:17:21
【问题描述】:
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"] 列表。

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

【问题讨论】:

  • 使用generator,即yield关键字代替return。当您使用return 时,您的函数将永远退出。您的其余代码对我来说并不完全清楚,但一个问题肯定是您在 main_func 中的循环在一次迭代后结束。
  • 投票结束。可笑的是不清楚预期的行为是什么。

标签: python list function


【解决方案1】:

把你的函数变成一个生成器:

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']

【讨论】:

    【解决方案2】:

    假设你有一个变量:

    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
    

    希望这有帮助!

    【讨论】:

      猜你喜欢
      • 2017-03-03
      • 2019-04-22
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 2017-12-01
      • 1970-01-01
      • 2020-12-18
      相关资源
      最近更新 更多