【问题标题】:PYTHON parameter passing with lists使用列表传递 PYTHON 参数
【发布时间】:2016-03-21 14:54:25
【问题描述】:

将参数传递给我的函数时,它不会识别列表并输出字符串。

游戏叫传猪,需要输出猪落地的状态。

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

提前感谢您的帮助!

代码如下:

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)

【问题讨论】:

  • 我不明白 if ... == x 结构;在任何情况下,第一次比较都将返回 0 或 1,这小于所有 y 常量,如 35、65....
  • ¯|_(ツ)_/¯ 嗯不确定
  • @guidot:不完全是。 a == b &lt; c 不被解析为(a==b) &lt; c,而是(a == b) and (b &lt; c),因为这是一个链式比较。当然,仍然不是预期的。 :-)

标签: python list parameter-passing


【解决方案1】:

我假设您希望 if List[listpos] == 1&lt; 35 表示 List[listpos] 介于 1 和 35 之间,不包括 35。 写法是:

if 1 <= List[listpos] < 35:

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

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

等等。

【讨论】:

    【解决方案2】:

    我的声誉太低,无法发表评论,但我会尝试稍微澄清一下代码并给出我的答案。

    对于初学者,你应该知道的一件事是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] &gt;= 1 and list_name[listpos] &lt; 35

    我确信有一种更短的方法可以做到这一点,但这会帮助您将其可视化为一系列值。

    【讨论】:

      【解决方案3】:

      由于只有 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])
      

      【讨论】:

        猜你喜欢
        • 2016-09-05
        • 2011-02-12
        • 2011-01-20
        • 2012-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        相关资源
        最近更新 更多