简体   繁体   English

这两个代码有什么区别?

[英]What's the difference between these two codes?

I recently started coding in Python 2.7. 我最近开始使用Python 2.7进行编码。 I'm a molecular biologist. 我是一名分子生物学家。 I'm writing a script that involves creating lists like this one: 我正在编写一个涉及创建这样的列表的脚本:

mylist = [[0, 4, 6, 1], 102]

These lists are incremented by adding an item to mylist[0] and summing a value to mylist[1]. 通过向mylist [0]添加项目并将值与mylist [1]相加来增加这些列表。

To do this, I use the code: 为此,我使用代码:

def addres(oldpep, res):
    return [oldpep[0] + res[0], oldpep[1] + res[1]]

Which works well. 哪个效果很好。 Since mylist[0] can become a bit long, and I have millions of these lists to take care of, I thought that using append or extend might make my code faster, so I tried: 由于mylist [0]可能会变得有点长,并且我有数以百万计的这些列表需要处理,我认为使用append或extend可能会使我的代码更快,所以我试过:

def addres(pep, res):
    pep[0].extend(res[0])
    pep[1] += res[1]
    return pep

Which in my mind should give the same result. 在我看来应该给出相同的结果。 It does give the same result when I try it on an arbitrary list. 当我在任意列表上尝试它时,它确实给出了相同的结果。 But when I feed it to the million of lists, it gives me a very different result. 但是当我将它提供给数百万个列表时,它给了我一个非常不同的结果。 So... what's the difference between the two? 那么......两者之间有什么区别? All the rest of the script is exactly the same. 脚本的其余部分完全相同。 Thank you! 谢谢! Roberto 罗伯托

The difference is that the second version of addres modifies the list that you passed in as pep , where the first version returns a new one. 不同之处在于, addres的第二个版本修改了您作为pep传递的列表,其中第一个版本返回一个新版本。

>>> mylist = [[0, 4, 6, 1], 102]
>>> list2 = [[3, 1, 2], 205]
>>> addres(mylist, list2)
[[0, 4, 6, 1, 3, 1, 2], 307]
>>> mylist
[[0, 4, 6, 1, 3, 1, 2], 307]

If you need to not modify the original lists, I don't think you're going to really going to get a faster Python implementation of addres than the first one you wrote. 如果您需要在不改变原来的名单,我不认为你会真的要获得更快的Python实现的addres比你写的第一个。 You might be able to deal with the modification, though, or come up with a somewhat different approach to speed up your code if that's the problem you're facing. 但是,您可能能够处理修改,或者提出一种稍微不同的方法来加速代码,如果这是您面临的问题。

List are objects in python which are passed by reference. List是python中的对象,通过引用传递。

a=list() α=清单()

This doesn't mean that a is the list but a is pointing towards a list just created. 这并不意味着a是列表,而是指向刚刚创建的列表。

In first example, you are using list element and creating a new list, an another object while in the second one you are modifying the list content itself. 在第一个示例中,您使用列表元素并创建新列表,另一个对象,而在第二个示例中,您正在修改列表内容本身。

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

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