【问题标题】:A function that takes in both a list (myList) and a value (n) and checks whether or not the value is in that list一个函数,它同时接受一个列表 (myList) 和一个值 (n) 并检查该值是否在该列表中
【发布时间】:2016-03-05 05:28:20
【问题描述】:

我想知道是否有人新如何在 python 中解决这个问题? 编写一个函数,它同时接受一个列表 (myList) 和一个值 (n),并检查该值是否在该列表中。如果列表中确实存在该值,则将其替换为值“1”。您的函数应该返回更新后的列表。使用函数签名:def replaceNum(myList, n):

示例:如果函数的输入是 replaceNum([12, 6, 10, 10], 10),则该函数将返回一个包含 [12, 6, 1, 1] 的列表。

到目前为止我有这个

def replaceNum(myList,n):
    new_list = []
    for i in range(0, len(myList)):
        if i == n:
            myList[n] = 1
            new_list.append(i)

        return myList[i]
print(replaceNum([5, 10, 20], 10))

但它只打印一个 5,我需要它来打印 [5,1,20]

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以使用list comprehension 来完成此操作。该函数遍历myList 中的每个元素,如果它等于n,则将其替换为1

    def replaceNum(myList, n):
        return [x if x != n else 1 for x in myList] 
    
    print(replaceNum([5, 10, 20], 10))
    

    输出

    [5, 1, 20]
    

    【讨论】:

    • @ZAMUEL123 我认为你需要 15 声望才能投票
    【解决方案2】:

    专注于修复代码。

    主要问题之一是您在循环内部返回。不仅如此,您只返回了来自myList 的单个项目。

    相反,您应该做的是设置您的 for 循环以使用 for i, v enumerate(myList) 迭代您的索引和值,然后在找到匹配项时更改值。

    像这样:

    def replaceNum(myList,n):
        for i, v in enumerate(myList):
            if v == n:
                myList[i] = 1
        return myList
    print(replaceNum([5, 10, 20], 10))
    

    然后进一步优化,看gtlambert's的回答

    【讨论】:

      猜你喜欢
      • 2012-02-15
      • 2021-03-19
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      相关资源
      最近更新 更多