python - Create range without certain numbers -


i want create range x 0 ... n, without of numbers in list y. how can this?

for example:

n = 10 y = [3, 7, 8] x = # 

should give output:

x = [0, 1, 2, 4, 5, 6, 9] 

one naive way concatenate several ranges, each spanning set of numbers have been intersected numbers in y. however, i'm not sure of simplest syntax in python.

you can use list comprehension filter range 0 n: range(n) generates list (or, in python 3, generator object) 0 n - 1 (including both ends):

x = [i in range(n) if not in y] 

this filters out numbers in y range.

you can turn generator (which iterate on once faster (very) large n) replacing [ ( , ] ). further, in python 2, can use xrange instead of range avoid loading entire range memory @ once. also, if y large list, can turn set first use o(1) membership checks instead of o(n) on list or tuple objects. such version might like

s = set(y) x = (i in range(n) if not in s) 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -