Python 从数学函数自动生成列表?

Python 从数学函数自动生成列表?,python,list,python-3.6,collatz,Python,List,Python 3.6,Collatz,我的想法是在任意范围内对以1、3、7和9结尾的数字运行3n+1进程(),并告诉代码将每个动作的长度发送到一个列表,这样我就可以分别在该列表上运行函数 到目前为止,我已经将单位数字1、3、7和9指定为:如果n%10==1如果n%10==3…等等,我认为我的计划需要某种形式的嵌套for循环;我使用列表追加的地方是让temp=[]和leng=[]在每次输入leng之前,找到一种方法让代码自动temp.clear()。我假设有不同的方法可以做到这一点,我愿意接受任何想法 leng = [] temp =

我的想法是在任意范围内对以1、3、7和9结尾的数字运行3n+1进程(),并告诉代码将每个动作的长度发送到一个列表,这样我就可以分别在该列表上运行函数

到目前为止,我已经将单位数字1、3、7和9指定为:
如果n%10==1
<代码>如果n%10==3…等等,我认为我的计划需要某种形式的嵌套for循环;我使用列表追加的地方是让
temp=[]
leng=[]
在每次输入
leng
之前,找到一种方法让代码自动
temp.clear()
。我假设有不同的方法可以做到这一点,我愿意接受任何想法

leng = []
temp = []
def col(n):
    while n != 1:
        print(n)
        temp.append(n)
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
    temp.append(n)
    print(n)

现在还不清楚你具体在问什么,想知道什么,所以这只是一个猜测。因为您只想知道序列的长度,所以实际上不需要在每个序列中保存数字,这意味着只创建了一个列表

def collatz(n):
    """ Return length of Collatz sequence beginning with positive integer "n".
    """
    count = 0
    while n != 1:
        n = n // 2 if n % 2 == 0 else n*3 + 1
        count += 1
    return count

def process_range(start, stop):
    """ Return list of results of calling the collatz function to the all the
        numbers in the closed interval [start...stop] that end with a digit
        in the set {1, 3, 7, or 9}.
    """
    return [collatz(n) for n in range(start, stop+1) if n % 10 in {1, 3, 7, 9}]

print(process_range(1, 42))
输出:

[0, 7, 16, 19, 14, 9, 12, 20, 7, 15, 111, 18, 106, 26, 21, 34, 109]

你的问题到底是什么?这正是我想要的,我不知道这种代码在工作时是什么样子的,我在其他任何地方都找不到。