I want to generate multiple ( n
number) 9 digit
random numbers in one go in python and then add a prefix digit (say 1) to each of these numbers (making them 10 digit numbers) and then write them to a file? I know how to generate a single random number using:
import random
random.randint(100000000,999999999)
But how do I generate multiple numbers in one go and then a add predetermined prefix digit to each of them before writing them to a file?
Here I am doing for 10 numbers which are generated randomly , do it for how many numbers you want,
import random
for i in range (10):
ang = random.randrange(100000000,999999999)
print int("1"+str(ang))
You can do something like this:
import random
file = open("output.txt", "ab")
def generate_random(n):
for i in range(n):
number = random.randint(1100000000, 1999999999) #No need to ppend 1 after generating number.
file.write(str(number)+"\n")
generate_random(10)
So the output file looks like this:
1972697009
1588689225
1801344328
1405227028
1801903655
1868723502
1358721529
1394641572
1104858492
1694223145
Hope this helps.
You sound like you might be interested in random.sample
. However, sample explicitly only produces unique values unless there are duplicate values in the population. This may or may not be what you want.
With sample you could do something like:
import random
prefix = 1 # or something like "#1" if that's what you want
digits = 9
num_samples = 9
values = random.sample(range(10**digits), num_samples)
strings = ["{}{:0{}}".format(prefix, v, digits) for v in values]
with open("yourfile.txt", "w") as f:
print(*strings, sep="\n", file=f)
Just select a random sample of 9 numbers in the final 10-digit range. This also ensures that each number in the resulting list will be unique.
import random
numbers = xrange(1000000000, 2000000000)
sample = random.sample(numbers, 9)
print(sample)
Output:
[1705109241, 1634244584, 1769529233, 1858322249, 1266131804, 1019067146,
1781176897, 1274126811, 1216604448]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.