我如何进行随机选择。如何生成多个数字?

2024-04-25 20:44:38 发布

您现在位置:Python中文网/ 问答频道 /正文

import threading
import time
from colorama import init, Fore
import ctypes
import string
import random

init(convert=True)
ctypes.windll.kernel32.SetConsoleTitleW("Number Generator")

f = open('capodepera.txt', 'a')
print()
print(Fore.RED + 'Enter amount of ips to generate: ')
amount = int(input())
fix = 1
while fix <= amount:
    code = ('').join(random.choices(string.digits.upper())) + "." + ('').join(random.choices(string.digits.upper()))  
    f.write(code.upper() + '\n')
    print(Fore.GREEN + code.upper())
    fix += 1
    ctypes.windll.kernel32.SetConsoleTitleW("generated ips: " + str(fix) + " from " + str(amount))

您好,所以我尝试制作一个IP生成器,但我不知道如何进行随机。选择(string.digits.upper())会生成多个数字。。我什么都试过了,但都补不上


Tags: fromimportstringinitcoderandomctypesfix
3条回答

随机选择并不是最好的选择。我建议改用random.randrange()

".".join(str(random.randrange(256)) for _ in range(4))

# '150.139.60.176'

您可能错过了documentation for ^{},它告诉您有一个名为k的参数:

random.choices(population, weights=None, *, cum_weights=None, k=1)
Return a k sized list of elements chosen from the population with replacement.

因此random.choices()返回一个大小为k的列表,其中k默认为1。如果要在返回的列表中包含多个值,请将k设置为其他值,例如k=3以获取值:

>>> import random, string
>>> random.choices(string.digits, k=3)
['0', '9', '0']

请注意,我没有为.upper()而烦恼。数字没有大写变体,它们不是字母

因此,要将两组具有.的数字连接在一起:

''.join(random.choices(string.digits, k=3) + '.' + ''.join(random.choices(string.digits, k=3)

或者使用f字符串,或者只导入choicesdigits

from random import choices
from string import digits

f"{''.join(choices(digits, k=3)}.{''.join(choices(digits, k=3)}"

但是,如果您试图生成IP地址,则使用random.choices()string.digits不是正确的选择。例如,IP地址通常不在开始时使用0

此外,您还被进一步限制为0到256之间的数字,并且某些数字是保留的(例如专用地址、多播地址、链路本地和环回网络以及其他保留地址),您可能不想生成那些

我将生成一个随机的32位数字(因此在range(2 ** 32)),将该数字馈送到^{},然后检查is_global标志以确保它是一个有效的全局IP地址(排除其他情况):

from ipaddress import IPv4Address

def random_ipv4():
    """Generate a random but valid global IPv4 address"""
    while True:
        address = IPv4Address(random.randrange(2 ** 32))
        if address.is_global:
            return str(address)   # convert to dot notation

这保证每次生成一个随机但有效的全局IP地址:

>>> print(random_ipv4())
124.34.255.74
>>> print(random_ipv4())
122.124.80.223
>>> print(random_ipv4())
50.242.11.192

你可以这样做

>>> import random
>>> random.choices(string.digits, k=20)
['4', '1', '5', '9', '7', '6', '4', '0', '4', '7', '6', '1', '9', '9', '4', '8', '5', '0', '1', '6']

相关问题 更多 >