简体   繁体   中英

How to generate phone numbers with itertools

I want to generate a file of all possible phone numbers with itertools.

from itertools import permutations
perm = list(permutations(['1','2','3','4','5','6','7','8','9','0'],7))
prefix = ['071','070','076','077','075']
file_to_write = open("numbers.txt",'w')
for pre in prefix:
    for per in perm:
        per = ''.join(per)
        file_to_write.write(pre+per+"\n")


file_to_write.close()`

this gives me a huge list of numbers but some numbers are missing because this cannot use one number twice in a combination as an example the list has not the item '0713025693' because the number three is repeated. What can I do. Please Help me.

Rather than using permutations , which does not allow duplicates, instead use product . In this case, you want:

from itertools import product

product(['1','2','3','4','5','6','7','8','9','0'], repeat=7)

or, as Boris points out, you can pass a string rather than a list (since strings are iterables), eg

product('1234567890', repeat=7)

Or you can import string and use:

product(string.digits, repeat=7)

For any of these, you could pass the result to list to produce a list, but it would be very long. It's preferable to leave it as an iterator, using it to iterate through the values without actually storing them in a list. Just beware that, as an iterator, if may only be traversed once, so if multiple passes are needed, you will need to recreate it.

use itertools.product (cartesian product) instead:

from itertools import product
list(product('ab', (0,1,2)))

[('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2)]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM