从一个输入中解包值以进行整数处理?

2024-10-01 13:35:11 发布

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

首先。我知道现在看起来很混乱,但是在将py2.7转换为py3.5代码时遇到了一个大问题,我还没有清理它。继续。我试图把所有的值解包为一行。这个代码工作,但不如我想。我可以输入从1到9的任何其他数字的值,这会起作用,但是如果我想掷1d20呢?还是10d4?我好像不能把整数分开。在py2.7和PY3.5中,由于我现在在这两个版本上都有一个工作代码,如果我(.split())或(.join(“”)变量,我仍然无法让它从'r3d4'行将整数作为单独的条目拉到一起。一旦我输入了一个两位数的数字,它就会出现一个错误“太多的值无法解包”,或者出现“int base 10”错误。有什么想法吗?我不想把它分成“你想掷多少骰子?”等等,我想要一个干净的单行条目。下面的代码在这里工作:https://www.onlinegdb.com/online_python_interpreter但是我不确定它是2.7还是3.5

import random
print("Dice Roller testing")
roll, amount, dice, sides = str(input("Input the format. example: r3d4. rolls 3d4 "))
amount = int(amount)
sides = int(sides)
i = 1 
while i <= amount and roll == "r" and sides == 4: 
    x = random.randint(1, 4) 
    print(x)
    i = (i+1) 
while i <= amount and roll == "r" and sides == 6: 
    x = random.randint(1, 6) 
    print(x)
    i = (i+1) 
while i <= amount and roll == "r" and sides == 8: 
    x = random.randint(1, 8) 
    print(x)
    i = (i+1) 
else: 
    print("We are finished or the input is not valid.")

NVM公司。知道了。你知道吗

明白了。这是我的密码。(python 3.6.4版)

import random
while True:
    user_input = str(input('test:  '))
    i = 1
    roll, sides = user_input.split("d")
    sides = int(sides)
    x, amount = roll.split("r")
    amount = int(amount)
    while i <= amount:
        n = random.randint(1,sides)
        print(n)
        i = i+1

Tags: and代码input数字整数randomamountint
1条回答
网友
1楼 · 发布于 2024-10-01 13:35:11

以滚动作为输入

import re
exp = re.compile('r?(\d{1,2})d(\d{1,2})')
try:
    amount, faces = exp.fullmatch(roll).group(1,2)
except AttributeError:
    print('bad format')

如果使用100个面或数量,则根据位数变化\d{1,2}(即:\d{1,3}

相关问题 更多 >