基于variab分配字符串的循环

2024-09-29 23:20:29 发布

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

我有多个IP地址,范围从xxx.xx.xxx.11xxx.xx.xxx.50。 对于IPAddress .11,我想将字符串"A01"分配给变量cabine。 要对.12进行IPAddress,字符串"A02"etc直到.30"A20"

然后,从IPAddress.31,我想将字符串"B01".32{}等一直添加到.50{}

虽然我是一个绝对的初学者,我认为这不会那么难,但它只是不想工作

我想用for循环编程,类似这样:

for (i = 11; i < 51; i++) {
  cabine = A and something with i;
}

但我需要两个不同的循环,因为字母(A,B)不同,对吗? 提前感谢您的帮助


Tags: and字符串for编程etcsomethingxxxipaddress
3条回答

以下是您想要的示例:

cabine = []

data = ["xxx.xx.xxx.11" , "xxx.xx.xxx.24", "xxx.xx.xxx.34", "xxx.xx.xxx.45", "xxx.xx.xxx.49", "xxx.xx.xxx.50"]

for val in data:
  number = int(val[-2:])
  if(number > 10 and number<=30):
    cabine.append("A{:02d}".format(number - 10))
  elif(number > 30 and number<=50):
    cabine.append("B{:02d}".format(number - 30))

print(cabine)

使用if语句确定前缀AB,以及循环索引如何转换为后缀号。然后使用格式化运算符添加前导零(请参见Best way to format integer as string with leading zeros?

for i in range(11, 51):
    if i <= 30:
        prefix = 'A'
        num = i - 10
    else:
        prefix = 'B'
        num = i - 30
    cabine = f'{prefix}{num:02d}'

要处理IP地址,可以使用ipaddress模块。.packed成员可以访问IPV4Address的每个号码。然后,您需要一个将IP地址转换为a/B和所需号码的公式

from ipaddress import IPv4Address

def gen_name(ip):
    i = IPv4Address(ip).packed[3]
    return f"{'A' if i < 31 else 'B'}{(i-11)%20+1:02}"

for i in range(11,51):
    ip = f'192.168.1.{i}' # generate IPs for testing
    name = gen_name(ip)
    print(ip,name)

输出:

192.168.1.11 A01
192.168.1.12 A02
192.168.1.13 A03
192.168.1.14 A04
192.168.1.15 A05
192.168.1.16 A06
192.168.1.17 A07
192.168.1.18 A08
192.168.1.19 A09
192.168.1.20 A10
192.168.1.21 A11
192.168.1.22 A12
192.168.1.23 A13
192.168.1.24 A14
192.168.1.25 A15
192.168.1.26 A16
192.168.1.27 A17
192.168.1.28 A18
192.168.1.29 A19
192.168.1.30 A20
192.168.1.31 B01
192.168.1.32 B02
192.168.1.33 B03
192.168.1.34 B04
192.168.1.35 B05
192.168.1.36 B06
192.168.1.37 B07
192.168.1.38 B08
192.168.1.39 B09
192.168.1.40 B10
192.168.1.41 B11
192.168.1.42 B12
192.168.1.43 B13
192.168.1.44 B14
192.168.1.45 B15
192.168.1.46 B16
192.168.1.47 B17
192.168.1.48 B18
192.168.1.49 B19
192.168.1.50 B20

相关问题 更多 >

    热门问题