在列表中重复i次 - n次

时间:2016-10-03 13:14:40

标签: python python-3.x

经过一些混乱(可能不是由于我的问题一直是一个不好的问题引起的)我正在尝试如何实现代码来执行以下操作,但n次:

def 1_level:
    for i in list:
        for j in i:
            mylist.append(i)

def 2_levels:
    for i in list:
        for j in i:
            for k in j:
                mylist.append(k)

def 3_levels:
    for i in list:
        for j in i:
            for k in j:
                for l in k:
                    mylist.append(l)

def 4_levels:
    for i in list:
        for j in i:
            for k in j:
                for l in k:
                    for m in l:
                        mylist.apend(m)

def 5_levels:
    for i in list:
        for j in i:
            for k in j:
                for l in k:
                    for m in l:
                        for n in m:
                            mylist.append(n)

我的想法如下:

def prunelist(n,mylist):
    if n > 0:                          # if n has not been reached
        for i in mylist:
            templist = []              #create blank list for appended items
            for j in i:
                templist.append(j)     #append items one branch down
            mylist = templist          #overwrite original list 
            n -= 1                     #reduce n by 1 
            prunelist(n,mylist)        #perform operation again (assuming n >0)

    else:
        return mylist              #when n is exhausted, output list

outputlist = prunelist(n,mylist)       #perform operation

(有关更多漫无边际的解释,请参阅编辑!!!)

干杯

J-P

1 个答案:

答案 0 :(得分:2)

您的prunelist功能几乎就在那里,只有几个问题:

  • 您只需执行mylist = templist即可覆盖传递的列表。这会修改mylist变量,但不会修改原始变量。您可以在此处替换原始列表的内容,但更好的方法是返回新列表(即templist)。这也适用于返回未修改mylist
  • 的其他递归情况
  • 在每次迭代mylist中,您都会丢弃上一次迭代的结果。将templist = []初始化移到循环外部,return prunelist(n, templist)也移动

如果你这样做,你的功能已经有效:

def prunelist(n, mylist):
    if n > 0:
        templist = []
        for i in mylist:
            for j in i:
                templist.append(j)
        return prunelist(n - 1, templist)
    else:
        return mylist