我如何对函数进行排序?
How can i sort a function?
我想用这段代码做的是掷 'n' 个骰子,然后找到它的下四分位数。
到目前为止我有:
from random import randint
#Rolling the Die
numofdie = int(input("Please input the number of dice u want to roll: "))
if numofdie < 1:
print ("PLease enter 1 or more")
quit()
if numofdie > 100:
print ("PLease enter a number less than 100")
quit()
#Sum
def dicerolls():
return [randint(1,6) for _ in range(numofdie)]
print (dicerolls())
然后我使用 string.sort() 函数尝试对 dicerolls() 进行排序,但意识到它不会工作,因为它是一个函数。我该如何解决这个问题,然后才能找到下四分位数。
谢谢
内置的 sorted()
函数将 return 您提供的任何列表的排序版本。由于 dicerolls()
return 是一个列表,您可以直接将该列表添加到:
print(sorted(dicerolls()))
将结果放入一个变量中,然后对其进行排序。
rolls = dicerolls()
rolls.sort()
print(rolls)
或使用sorted()
函数:
print(sorted(dicerolls())
我想用这段代码做的是掷 'n' 个骰子,然后找到它的下四分位数。
到目前为止我有:
from random import randint
#Rolling the Die
numofdie = int(input("Please input the number of dice u want to roll: "))
if numofdie < 1:
print ("PLease enter 1 or more")
quit()
if numofdie > 100:
print ("PLease enter a number less than 100")
quit()
#Sum
def dicerolls():
return [randint(1,6) for _ in range(numofdie)]
print (dicerolls())
然后我使用 string.sort() 函数尝试对 dicerolls() 进行排序,但意识到它不会工作,因为它是一个函数。我该如何解决这个问题,然后才能找到下四分位数。
谢谢
内置的 sorted()
函数将 return 您提供的任何列表的排序版本。由于 dicerolls()
return 是一个列表,您可以直接将该列表添加到:
print(sorted(dicerolls()))
将结果放入一个变量中,然后对其进行排序。
rolls = dicerolls()
rolls.sort()
print(rolls)
或使用sorted()
函数:
print(sorted(dicerolls())