random - Python sample without 0 -


i need sample k numbers in [-n,-1] union [1,n] without replacement. why doesn't code work?

random.sample(range(-n,n+1).remove(0),k) 

i

traceback (most recent call last):   file "<input>", line 1, in <module>   file "/usr/lib/python2.7/random.py", line 319, in sample     n = len(population) typeerror: object of type 'nonetype' has no len() 

remove inplace operation. modifies list, , returns none. that's why seeing error. should create list separately , pass sample:

>>> l = range(-n, n+1) >>> l.remove(0) >>> random.sample(l, k) 

if want in 1 statement, create 2 parts of range separately , add them.

>>> random.sample(range(-n, 0) + range(1, n+1), k) 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -