1. 程式人生 > >Difference between Range and Xrange in Python

Difference between Range and Xrange in Python

概述

之前在stackoverflow上看見一個答案描述Python中range與xrange的區別:
range的返回值是一個list,包含所有範圍內滿足條件的元素;
而Xrange的返回值是一個xrange的Object,通過協程,在每次呼叫時執行一次生成下一個元素的物件。
(在文件中可以找到類似的表述)

也就是說range是一次生成所有元素並返回list,而xrange是在每次呼叫時生成一個;換言之,xrange對記憶體會更加友好。

舉一個栗子

在瞭解這個答案後我的印象中一直認為xrange貌似要比range好一點,不過一直沒有一個直觀的印象。
直到最近嘗試做ProjectEuler的一個題:

Highly divisible triangular number

無腦地直接寫了一個暴力的解法:

triangular = 0
triangular_step = 0


def triangular_num():
    global triangular_step, triangular
    # make step add 1, and figure out triangular num
    triangular_step += 1
    triangular += triangular_step


def divisor_num(digit):
    num = 0
    for
tmp in range(1, digit + 1): if digit % tmp == 0: num += 1 return num if __name__ == "__main__": while True: triangular_num() dn = divisor_num(triangular) with open('./out.txt', 'a') as f: f.write(str(triangular) + ' : ' + str(dn) + '\n'
) if dn > 500: break

執行時發現記憶體的使用量高達幾百,並且很穩定地向上增長:
python2.7-range

之後我將range改為xrange:
python2.7-xrange
記憶體由此穩定在3.5M左右。

注與吐槽

說明一下,筆者使用的Python是2.7的版本,在Python3中range的功能已由xrange替換,所以你可以放心大膽地用range而不用擔心記憶體的問題。

吐槽:
筆者也想用Python3,python3中很多特性都非常好,不過無奈更新太頻繁,很多元件都不支援。
學習中的一點小體會,寫出來與大家分享一下。

相關推薦

Difference between Range and Xrange in Python

概述 之前在stackoverflow上看見一個答案描述Python中range與xrange的區別: range的返回值是一個list,包含所有範圍內滿足條件的元素; 而Xrange的返回值是一個xrange的Object,通過協程,在每次呼叫時執行一次

The Difference between #define and const in C/C++

The Difference between #define and const in C/C++I was recently asked an interesting question by one of my friends who is currently learning to program in

what is the difference between Integer and int in java?

ive rim ever pan long () bool out com int is a primitive type, Variables of int type store the actual binary value for the Integer type y

Difference between HashMap and Hashtable in Java

1.The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null valu

What is the difference between Kill and Kill -9 command in Unix?

data esp osi lin mil print ren win sku w difference kill -9 pid and kill pid command - Ask Ubuntu https://askubuntu.com/questions/7918

Relationship between frequency and spatial in digital images

log 兩個 表示 title cal .com 關系 show tla 今天又復習了一遍<<Digital Image Processing>>的第四章,為了加深對頻域的理解,我自己用PS畫了一張圖。如下: 然後做FFT,得到頻譜圖如下:

【轉載】What is the difference between authorized_keys and known_hosts file for SSH?

led accounts dep protocol wide HERE data round enc The known_hosts file lets the client authenticate the server, to check that it isn‘t c

Difference between Netbios and Host name

recommend resolv vid should hostname domain win ebo score Hostnames or NetBIOS names were used to provide a friendlier means of identifyi

what's the difference between Rlock and Lock?

來自StackOverflow上的問答: The main difference is that a Lock can only be acquired once. It cannot be acquired again, until it is released. (Af

Difference between orc and parquet format

參考: https://www.cnblogs.com/ITtangtang/p/7677912.html https://blog.csdn.net/yu616568/article/details/51868447 https://hortonworks.com/blog/orcfi

(The difference between Comparator and Comparable)Comparator和Comparable的區別

來源於 https://blog.csdn.net/zhushuai1221/article/details/51760663 in view of https://blog.csdn.net/zhushuai1221/article/details/51760663 原始碼(sou

the difference of copyto() and clone() in opencv

clone :完全拷貝 copyto :只是拷貝資料區 過載運算子()和 = 操作都屬於淺拷貝。clone()和copyto()屬於深拷貝. 這兩者的不同在於,copyto()多了一個mask玩法,即過

Difference between object and class

1. object is the instance of a class.  class defined the blueprint or template of a object, include its behavior and/or perproies. 2. object is

difference between truncate and delete

1. delete a data entry operation will be recored in the db log, and can be rollback by log. the related trigger could be triggered.   &nbs

How to use *args and **kwargs in Python

這篇文章寫的滿好的耶,結論: 1星= array, 2星=dictionary. 1星範例: def test_var_args(farg, *args): print "formal arg:", farg for arg in args: print "an

How To Communicate Between Fragments and Activities in Android

Welcome to: how to communicate between fragments and activities in your android applications. If you have not done so already, please check out my previ

Ask HN: The difference between “overvalued” and “that's how much it is now”?

I'm particularly interested in housing prices, but if it's different for other industries I'd love to understand that as well.It's strangely hard to find a

Why the difference between AI and machine learning matters

This article is part of Demystifying AI, a series of posts that (try) to disambiguate the jargon and myths surrounding AI. A while ago, while browsing thro

Customer Profiling and Segmentation in Python An Overview & Demo

While most marketing managers understand that all customers have different preferences, these differences still tend to raise quite a challenge when it com

lambda, map and filter in Python

lambda, map and filter in Pythonlambdalambda operator or lambda function is used for creating small, one-time and anonymous function objects in Python.Basi