小编tib*_*ish的帖子

列表列表中子列表的最大和

在Python中迈出第一步。我有一个列表的列表,我试图返回的子列表的所有子列表的最大的一笔。现在,我只拥有最大和。例如:此代码返回18,但我需要返回[3,3,3,3,3,3]

有方向吗?谢谢

def find_biggest(lst):
    inner_list_sum = []
    for i in range(len(lst)):
        inner_list_sum.append(sum(lst[i]))    # list of elements sums
    return max(inner_list_sum)                # I actually need the element itself...not the max sum

print(find_biggest([[1,2,3,4], [1,2,3,3], [1,1], [3,3,3,3,3,3]]))

Run Code Online (Sandbox Code Playgroud)

python python-3.x python-requests

2
推荐指数
1
解决办法
35
查看次数

Closure : 一个函数,它返回上一次调用的值

我正在尝试构建一个函数,该函数使用闭包返回其先前调用的值。第一次调用函数时,它将返回 None。我不确定如何将 last_in 从一个调用更新到另一个调用。

def last_in(x):
    last_in = [None]

    def get():
        temp = last_in[0]
        last_in[0] = x
        # print(last_in)
        return temp
    return get()

Run Code Online (Sandbox Code Playgroud)

例如,print(last_in(1),last_in(2),last_in(3))应该打印:None 1 2

python

2
推荐指数
1
解决办法
340
查看次数

无需理解的嵌套列表

在Python中迈出第一步:)

我正在尝试获得以下输出:[[1],[1、2],[1、2、3],[1、2、3、4],[1、2、3、4、5] ,...,[1、2、3、4,...,n]]

例如:n = 4 [[1],[1、2],[1、2、3],[1、2、3、4]

不能 /不允许使用列表理解。

这是我尝试的:

def lists(n):
    matrix = []
    for i in range(1, n+1):
        matrix.append([])
        for j in range(1,i+1):
            matrix[i].append(j)
    print(matrix)

lists(5)
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:IndexError:列表索引超出范围。

这是为什么?将不胜感激

python python-3.x

1
推荐指数
1
解决办法
82
查看次数

标签 统计

python ×3

python-3.x ×2

python-requests ×1