骰子是函数中的一个变量,没有包含在此代码中,但它生成了一个1到6之间的5个随机数的列表。下面的函数我正在尝试实现,以便用户可以选择列表中的哪个索引,他们想使用输入来更改。接受用户的输入,它会将列表中的索引更改为1到6之间的新随机数。我在下面尝试过,但这是一个非常漫长的过程,有没有其他方法?
def reroll(dice):
rollagain = str(input("Which dice would you like to re-roll, input in ascending order (options are: 1,2,3,4,5): "))
if rollagain == '1,2,3,4,5':
dice[0, 1, 2, 3, 4].append = [randint(1, 6)]
return True
elif rollagain == '1,2,3,4':
dice[0, 1, 2, 3].append = [randint(1, 6)]
return True
elif rollagain == '1,2,3':
dice[0, 1, 2].append = [randint(1, 6)]
return True
elif rollagain == '1,2':
dice[0, 1].append = [randint(1, 6)]
return True
elif rollagain == '1':
dice[0].append = [randint(1, 6)]
return True
elif rollagain == '1,3,5':
dice[0, 2, 4].append = [randint(1, 6)]
return True
elif rollagain == '2, 4':
dice[1, 3].append = [randint(1, 6)]
return True
elif rollagain == '2':
dice[1].append = [randint(1, 6)]
return True
elif rollagain == '3':
dice[2].append = [randint(1, 6)]
return True
elif rollagain == '4':
dice[3].append = [randint(1, 6)]
return True
elif rollagain == '5':
dice[4].append = [randint(1, 6)]
return True
elif rollagain == '1,4,5':
dice[0, 3, 4].append = [randint(1, 6)]
return True
elif rollagain == '1,2,5':
dice[0, 1, 4].append = [randint(1, 6)]
return True
else:
return False发布于 2014-12-01 07:47:51
尝试将"rollagain“拆分成一个元组,然后传递给"dice”。这应该会缩短一点:-)
发布于 2014-12-01 07:53:52
我想我明白你想做什么了。(假设dice是一个列表,如果不是,只需更改赋值)
试试这个:
def reroll(dice):
rollagain = str(input("Which dice would you like to re-roll, input in ascending order (options are: 1,2,3,4,5): "))
for combo in [[0,1,2,3,4],[0,1,2,3],[0,1,2],[0,1],[0],[0,2,4],[1,3],[1],[2],[3],[4],[0,3,4],[0,1,4]]:
if rollagain == ','.join(map(lambda x: str(x+1), combo)):
for index in combo:
dice[index] = randint(1, 6)
return True
return False发布于 2014-12-01 07:56:31
下面的代码只能在您似乎正在使用的Python 3.x中工作。如果您使用的是Python2.x,则内置的input具有不同的行为。
我所理解的是,用户可以选择必须修改原始dice的哪些索引,对吧?如果是这样的话,因为input足够聪明,可以将2,3求值为整数(2,3)的元组,所以您可以使用如下代码:
rollagain = input("Which dice would you like to re-roll,"
" input in ascending order (options are: 1,2,3,4,5): ")
indexes_to_change = [int(index) for index in rollagain.split(',')]
print "User wants to change: %s" % (indexes_to_change)
print "Before change, the dice list is: %s" % dice
for index_to_change in indexes_to_change:
dice[index_to_change-1] = random.randint(1, 6)
print "After change, the dice list is: %s" % dice我添加了一些print语句,它们可能有助于理解所发生的事情。您还应该了解Python字符串的split方法,以及如何将包含数值的字符串转换为实际的int (参见this SO thread)。
你也应该读一读关于Exceptions的文章。如果用户决定输入"foo"而不是一些逗号分隔的数字,您可能需要它们。
此外,如果您正在使用Python < 3,与我的想法相反,您应该考虑使用raw_input而不是input,因为input (在Python <3中)使用eval和eval is evil。
https://stackoverflow.com/questions/27219678
复制相似问题