【问题标题】:Iterating list within tuple元组内的迭代列表
【发布时间】:2014-10-10 21:02:10
【问题描述】:

有了这个:

a = [(string,[(string,integer)])]

我想做

for i in range(len(a)):
    for j in range(len(a[i][1])):
        var = a[i][1][1] # get the integer value

但没有循环(函数式编程)。

有人可以帮帮我吗?提前致谢。

【问题讨论】:

  • 循环,抱歉。固定。
  • 取决于# stuff 是什么。
  • len(a) 是一个整数(不可迭代)。 for-loops 需要迭代。您可能的意思是for i in range(len(a)) ... a[i] 在Python 中更惯用地写为for e in a ... e
  • 迭代然后做什么?
  • 谢谢,user4122880,你说得对

标签: python list functional-programming tuples


【解决方案1】:

我想你想做这样的事情:

def ListIterator(somelist):
    if len(somelist) == 0:
        return
    elif somelist[0] == isinstance(somelist,list):
        ListIterator(somelist[0])
    else:
        #dostuff

【讨论】:

  • 感谢您的回复。但是,即使我不能用这个作为解决方案,那不就是elif isinstance(somelist[0],list):吗?
【解决方案2】:

为了将来参考,这行得通:

def main(lst):
    if lst == []
        return
    aux(lst[0][1])
    return main(lst[1:])

def aux(lst):
    if lst == []
        return
    x = lst[0][0] # I actually wanted the string, so I could get an index in another list,
                  # but lst[0][1] gives the int
    # stuff I wanted to do #
    return aux(lst[1:])

感谢所有回复。

【讨论】:

    猜你喜欢
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2015-01-20
    相关资源
    最近更新 更多