避免在python中使用对象别名? [英] Avoid object aliasing in python?

查看:128
本文介绍了避免在python中使用对象别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个函数来检查列表是否已排序(返回 True False )。如何避免多个变量指向同一事物?

I am trying to write a function to check whether a list is sorted (returning True or False). How can I avoid multiple variables pointing to the same thing?

def is_sorted(t):
    a = t
    a.sort()

当我这样做时,它会同时对进行排序a t 。如何避免这种情况?

When I do that, it sorts both a and t. How can I avoid this?

推荐答案

这是O(n)的实现方式

Here is the O(n) way to do it

>>> from itertools import islice, izip
>>> def is_sorted(L):
...     return all(i<=j for i,j in izip(L, islice(L,1,None)))
... 
>>> is_sorted(range(50))
True
>>> is_sorted(range(50)+[20])
False

它短路,所以如果列表在开始时就没有排序

It shortcircuits, so if the list is unsorted right near the beginning it will be very fast

这是一个比较某些替代方案的简单程序

Here is a simple program to compare some of the alternatives

import random
import time
from itertools import islice, izip

def is_sorted1(L):  # 0.0006s
    return all(i<=j for i,j in izip(L, islice(L,1,None)))

def is_sorted2(L):  # 0.117s
    return all(L[i] < L[i+1] for i in range(len(L)-1) )

def is_sorted3(L):  # 2.344s
    return L == sorted(L)

def is_sorted4(L):  # 0.0002s
    return all(L[i] < L[i+1] for i in xrange(len(L)-1) )

A = [range(random.randrange(100000)) for i in range(100)]
for a in A:
    random.shuffle(a)

for f in is_sorted1, is_sorted2, is_sorted3, is_sorted4:
    s=time.time()
    for a in A:
        f(a)
    print time.time() - s

这篇关于避免在python中使用对象别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆