简体   繁体   English

使用for循环创建新列表?

[英]Creating a new list using for loop?

I need to write a function that normalizes a vector (finds the unit vector). 我需要编写一个标准化向量的函数(查找单位向量)。 A vector can be normalized by dividing each individual component of the vector by its magnitude. 可以通过将向量的每个单独分量除以其大小来对向量进行归一化。

The input for this function will be a vector ie 1 dimensional list containing 3 integers. 该函数的输入将是一个向量,即包含3个整数的一维列表。

The code follows: 代码如下:

def my_norml(my_list):
    tot_sum = 0
    for item in my_list:
        tot_sum = tot_sum + item**2
    magng = tot_sum**(1/2)
    norml1 = my_list[0]/magng #here i want to use a for loop 
    norml2 = my_list[1]/magng
    norml3 = my_list[2]/magng
    return [norml1, norml2,norml3]

There's a couple of things you could do here. 您可以在这里做几件事。

Initially, let me just point out that tot_sum = tot_sum + item**2 can be written more concisely as tot_sum += item**2 . 最初,让我指出, tot_sum = tot_sum + item**2可以更简洁地写为tot_sum += item**2 To answer your question, you could use a loop to achieve what you want with: 要回答您的问题,您可以使用循环来实现您想要的功能:

ret_list = []
for i in my_list:
    ret_list.append(i / magng)
return ret_list

But this isn't the best approach. 但这不是最好的方法。 It is way better to utilize comprehensions to achieve what you need; 更好地利用理解力来实现您的需求; also, the sum built-in function can do summing for you instead of you needing to manually perform it with a for-loop : 同样, sum内置函数可以为您进行求和,而不需要使用for-loop手动执行:

magng can easily be computed in one line by passing a comprehension to sum . 通过将sum运算传递给sum可以轻松地在一行中计算出magng With the comprehension you raise each item to ** 2 and then immediately divide the summation that sum returns: 通过理解,您可以将每个item提高到** 2 ,然后立即将sum返回的总和除以:

magng = sum(item**2 for item in my_list) ** (1/2)

After this, you can create your new list by again utilizing a comprehension: 此后,您可以再次使用理解来创建新列表:

return [item/magng for item in my_list]

Which creates a list out of every item in my_list after dividing it by magng . 在用magng分隔my_list的每个item之后,该列表会创建一个列表。

Finally, your full function could be reduced to two lines (and one but that would hamper readability): 最后,您的全部功能可以简化为两行(但只有一行会影响可读性):

def my_norml(my_list):
    magng = sum(item**2 for item in my_list) ** (1/2)
    return [item/magng for item in my_list]

This is more concise and idiomatic and pretty intuitive too after you've learned comprehensions. 学习了理解后,这也更加简洁,惯用和直观。

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

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