2016-03-21 44 views
1

将参数传递给我的函数时,它不会识别列表并输出字符串。带有列表的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) 
+3

我不明白* if ...== x guidot

+0

¯| _(ツ)_ /¯umm不知道 –

+2

@guidot:不完全。 'a == b DSM

回答

0

我假设你想if List[listpos] == 1< 35意味着List[listpos]是1和35之间,没有被列入35 编写的方法是:

if 1 <= List[listpos] < 35: 

但是,在你的情况下,你并不真的需要3级的条件,因为只有第一个真正的if语句会运行。所以,你可以简单地做:

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

等等。

+0

谢谢,工作过一种享受! :-) –

0

我的评论声望太低,但我会尝试澄清一下代码并给出我的答案。

对于初学者,您应该知道的一件事是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作为参数,因为你是在函数的开始设置计数器为0,listlen可以与len()功能被发现。

其次,对于你的平等陈述,键入他们是这样的:

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

我敢肯定有一个较短的方式做到这一点,但是这会帮助你想象它作为一个范围值。

0

由于只有100个可能的卷(您不会将解释分配给0),因此还有一种替代方法:将查找表替换为映射卷到名称的if-elif-else更改。下面的代码是这样做的。它还创建了列表理解列表。

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])