如何为数组的子列表创建循环

时间:2021-08-01 11:11:39

标签: python

我正在尝试创建一个循环,其中对于子列表中的每个元素,我将其替换为公式。例如,

output = [[1, 2], [1, 4], [1, 6], [1, 8]]
y = 1**2 + 2
y2 = 1**2 + 4
y3 = 1**2 + 6
y4 = 1**2 + 8

等等。有没有简单的方法可以做到这一点?

3 个答案:

答案 0 :(得分:1)

您可以将子列表 [x, y] 分解xy,然后使用 list comprehension 将结果写入列表中,只使用一个代码行。 (感谢 Sujay 的评论)

results=[x**2+y for x, y in output]

这等于:

result = []
for x, y in output:
    result.append(x**2 + y)

答案 1 :(得分:0)

我认为你需要这样的东西:

def function(n):
    a = []
    for i in range(2, n*2 +2, 2):
        a.append([1, i])
    return a
print(function(5))

n=4 的输出:

[[1, 2], [1, 4], [1, 6], [1, 8]]

或者反向输入:

output = [[1, 2], [1, 4], [1, 6], [1, 8]]
def function(n):
    a = ""
    for i in range(len(n)):
        a += "y = 1**2 " + " + " + str(n[i][1]) + "\n"
    return a
print(function(output))

第二个代码的输出:

y = 1**2  + 2
y = 1**2  + 4
y = 1**2  + 6
y = 1**2  + 8

答案 2 :(得分:0)

我假设您的所有子列表都将包含 2 个元素。

您可以定义一个自定义函数operate_on_sublist,稍后您可以使用map 将其应用于每个子列表。检查下面的代码

def operate_on_sublist(output):
    return (output[0]**2) + output[1]

output = [[1, 2], [1, 4], [1, 6], [1, 8]]

squared = list(map(operate_on_sublist, output))

#Prints [3, 5, 7, 9]
print(squared)
相关问题