【问题标题】:Removing number from list of numbers从号码列表中删除号码
【发布时间】:2021-08-07 20:54:30
【问题描述】:

我正在尝试从数字列表中删除一个数字,但对于我的生活,我无法让它工作。

我尝试使用 list.remove() 方法和 .pop() 但它有些不起作用。最大是返回列表中最大数字的函数。我制作了列表的副本,因为问题要求的一部分是列表不被改变。当我尝试打印 bList 时,我得到了 None。

我还尝试通过引入变量 index = c.index(l) 来使用 .pop() 并使用也不起作用的 c.pop(index)。

def largest(aList):
    theLargest = aList[0]
    for i in range(1, len(aList)):
        if theLargest < aList[i]:
            theLargest = aList[i]
    return theLargest

def main():
    aList = [2,5,1,6]
    c = aList.copy()
    l = largest(c)
    bList = c.remove(l)
    print(bList)
main()
```

【问题讨论】:

标签: python arrays list function


【解决方案1】:

我修复了你的代码:

def largest(aList):
    theLargest = aList[0]
    for i in range(1, len(aList)):
        if theLargest < aList[i]:
            theLargest = aList[i]
    return theLargest


def main():
    aList = [2, 5, 1, 6]
    c = aList.copy()
    l = largest(c)
    # create a list without the largest num
    bList = c
    bList.remove(l)
    print(bList)


# Call your main function
main()

输出:

[2, 5, 1]

remove() 方法不返回新列表。 remove() 方法从列表中删除第一个匹配元素(作为参数传递)。

【讨论】:

    【解决方案2】:

    试一试: def 最大(aList): 最大的 = 一个列表 [0] 对于范围内的 i(1,len(aList)): 如果最大

    def main():
    aList = [2,5,1,6]
    c = aList.copy()
    l = largest(c)
    c.remove(l)
    print(c)
    main()
    

    【讨论】:

      【解决方案3】:

      remove() 就地工作,这意味着 l 将从 c 中删除,仅此而已,它不会返回新列表。

      所以你真的不需要bList,你可以从cprint(c)中删除l,就像这样:

      def main():
          aList = [2, 5, 1, 6]
          c = aList.copy()
          l = largest(c)
          c.remove(l)
          print(c)
      
      

      【讨论】:

      • 感谢您的回答和解释!
      猜你喜欢
      • 2023-01-08
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多