Python:迭代列表中的 true 和 false 变量,结果不同

Python: iterate over true and false variables in a list, with different outcomes

我正在编写一个类似 yahtzee 的游戏,玩家掷 5 个骰子并选择要重新掷的骰子。

我无法让我的函数正确迭代用户输入以验证它们是否有效。

这是一些代码:

def diceroll():
    raw_input("Press enter to roll dice: ")
    a = random.randint(1, 6)
    b = random.randint(1, 6)
    c = random.randint(1, 6)
    d = random.randint(1, 6)
    e = random.randint(1, 6)
    myroll.append(a)
    myroll.append(b)
    myroll.append(c)
    myroll.append(d)
    myroll.append(e)
    print "Your roll:"
    print myroll
    diceSelect()

def diceSelect():
    s = raw_input("Enter the numbers of the dice you'd like to roll again, separated by spaces, then press ENTER: ")    
    rollAgain = map(int, s.split())
    updateMyRoll(rollAgain)

def updateMyRoll(a):
    reroll = []
    for n in a:
        if n in myroll:
            reroll.append(n)
            removeCommonElements(myroll, a)
            print "deleting elements..."
        elif n not in myroll:
            print "I don't think you rolled", n, "."
            diceSelect()
        else:
            print "I don't understand..."
            diceSelect()
        print "Your remaining dice: ", myroll

def removeCommonElements(a,b,):
for e in a[:]:
    if e in b:
        a.remove(e)
        b.remove(e)

问题可能在 diceSelect 函数中,这样我只能输入真值并且它工作正常,我只能输入假值并仅获得第一个假值所需的效果(我根据代码...但想更改),或者我可以输入真值和假值,但它只作用于真值而忽略假值。

如何遍历这些值并重新提示用户输入所有真实值?

您的代码中存在一些问题。我稍微重写了您的代码:

def diceroll(dice_count=6):
    raw_input("Press enter to roll dice: ")
    # No need to create a variable for each roll.
    # Also modifying global variables is a bad idea
    rolls = []
    for _ in range(dice_count-1):
        rolls.append(random.randint(1,6))
    # or **instead** of the above three lines, a list
    # comprehension
    rolls = [random.randint(1,6) for _ in range(dice_count-1)]
    return rolls

def roll_select():
    # one letter variable names are hard to follow
    choices = raw_input("Enter the numbers of the dice you'd like to roll again, separated by spaces, then press ENTER: ")    
    # again, modifying global variables is a bad idea
    # so return the selection
    return map(int, choices.split())

def roll_new_dice(myroll):
    # no need to create a new list, we have everything
    # we need right here
    for val in roll_select():
        try:
            print('deleting {}'.format(val))
            # we can just remove the values directly. We'll get
            # an exception if they're not in the list.
            myroll.remove(val)
        except ValueError:
            print("That wasn't one of your rolls")
    # Then we can re-use our function - this time
    # extending our list.
    myroll.extend(diceroll(6-len(myroll)))

rolls = diceroll()
print('You rolled {}'.format(rolls))
changes = roll_select()
if changes:
    roll_new_dice(rolls)
print('Your new rolls: {}'.format(rolls))

希望这应该比您之前的内容更清楚一些。