用列表传递PYTHON参数

2024-06-16 11:33:50 发布

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

将参数传递到函数中时,它将无法识别列表并输出字符串。你知道吗

游戏名为传递猪,需要输出猪降落的状态。你知道吗

我知道有些地方的代码效率很低,尽管这是因为我一直在尝试不同的方法,但都没有成功:(

提前感谢您的帮助!你知道吗

代码如下:

norolls = int(input("Enter the number of rolls: "))
counter = 0

def roll(nothrows,counter):
    rollList = []
    while counter < nothrows:
        rollrand = randint(0,100)
        rollList.append(rollrand)
        counter = (counter + 1)
    return rollList

rollList = roll(norolls,counter)
rollList = list(map(int, rollList))
listlen = len(rollList)    

def rollout(List, listpos, ListLen):
    listpos = 0
    for x in range(ListLen):
        if List[listpos] == 1< 35:
            print("Pink")
        elif List[listpos] == 35 < 65:
            print("Dot")
        elif List[listpos] == 65< 85:
            print("Razorback")
        elif List[listpos] == 85 < 95:
            print("Trotter")
        elif List[listpos] == 95 < 99:
            print("Snouter")
        else:
            List[listpos] == 99 < 100
            print("Leaning Jewler")
        listpos = (listpos + 1)


rollout(rollList, counter, listlen)

Tags: 代码defcounterlistintprintrollelif
3条回答

我的声誉太低,无法发表评论,但我将尝试澄清一下代码并给出我的答案。你知道吗

对于初学者,有一点您应该知道list是一个保留名称,因此我不建议将它作为参数传递给任何函数。您应该将rollList传递给rollout(),因为这是您正在创建的列表。将列表作为参数传递的方法如下:

list_name = [1,2,3,4,5]

def function_name(myList=[]): for x in myList: print x

function_name(list_name)

注意函数定义中的myList=[]。你知道吗

我还要去掉counterlistlen作为参数,因为您在函数的开头将counter设置为0,并且listlen可以通过len()函数找到。你知道吗

其次,对于等式语句,请按以下方式键入:

if list_name[listpos] >= 1 and list_name[listpos] < 35

我相信有一个较短的方法可以做到这一点,但这将有助于你把它形象化为一系列的价值观。你知道吗

因为只有100个可能的roll(您没有将解释赋值给0),所以有一种替代方法:用一个将rolls映射到名称的查找表替换if else change。下面的代码就是这样做的。它还创建了一个具有列表理解的卷列表。你知道吗

from random import randint

rollmap = [None]
for sublist in (35*['Pink'], 30*['Dot'], 20*['Razorback'],
                10*['Trotter'], 4*['Snouter'], 1*['Leaning Jewler']):
    rollmap.extend(sublist)

n = int(input("Enter the number of rolls: "))
rolls = [randint(1, len(rollmap-1)) for i in range(n)]
for roll in rolls:
    print(rollmap[roll])

我假设你希望if List[listpos] == 1< 35意味着List[listpos]介于1和35之间,不包括35。 写作的方法是:

if 1 <= List[listpos] < 35:

但是,在您的例子中,实际上并不需要3级条件,因为只有第一个true if语句才会运行。所以,你可以简单地做:

if List[listpos] < 35:
    print("Pink")
elif List[listpos] < 65:
    ...

等等。你知道吗

相关问题 更多 >