简体   繁体   English

Python 嵌套循环问题python3.0

[英]Python Nested Loops questions python3.0

I'm trying to write a nested loop that calculates (x+y)^2 for every value of y where the outer loop should print (x+y)^2.我正在尝试编写一个嵌套循环,为外部循环应该打印 (x+y)^2 的每个 y 值计算 (x+y)^2。 Here is my code so far:到目前为止,这是我的代码:

x = [2,4,6,8,10,12,14,16,18]

y = [10,8.25,7.5,7,6.5,7,7.5,8.25,10]


for i in range(0 , len(x)):
# nested
    
    #for j in range(0, len(y)):
    for j in range(0, len(y)):
            
    
        print( (x[i] + y[j])**2)
        

My output keeps printing repeated values like so:我的 output 不断打印重复值,如下所示:

144
105.0625
90.25
81
72.25
81
90.25
105.0625
144

Maybe you could try this:也许你可以试试这个:

NB - it works by zipping through two lists (same size) and do the math.注意 - 它通过压缩两个列表(相同大小)并进行数学运算来工作。 If the size is unequal, then you should try zip_longest with some other default number (for this shorter list).如果大小不相等,那么您应该尝试 zip_longest 和其他一些默认数字(对于这个较短的列表)。


outs = []

for a, b in zip(x, y):
    outs.append(pow((a+b), 2))

Example 2: one list is longer -示例 2:一个列表更长 -

x = [2,4,6,8,10,12,14,16,18, 20]       # adding 20 as extra number

y = [10,8.25,7.5,7,6.5,7,7.5,8.25,10]

from itertools import zip_longest #(a, b, fillvalue=0)

outs = []

for a, b in zip_longest(x, y, fillvalue=0):
    outs.append(pow((a+b), 2))

Without using any library:不使用任何库:

print([((x[i] if i < len(x) else 0) + (y[i] if i < len(y) else 0))**2 for i in range(max(len(x), len(y)))])

OUTPUT OUTPUT

[144, 150.0625, 182.25, 225, 272.25, 361, 462.25, 588.0625, 784]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM