【问题标题】:List comprehension won't return expected output列表理解不会返回预期的输出
【发布时间】:2014-11-07 22:13:39
【问题描述】:

我正在尝试解决Google's Python Basic Exercises 并尝试解决这个关于列表理解的特定问题:

# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.
def remove_adjacent(nums):
  newList = []
  newList = [i for i in nums if len(newList) == 0 or nums[i] != newList[-1]]
  return newList

显然,输出不是我所期望的,作者制作的测试函数强调了这一点:

got: [2, 2, 3, 3, 3] expected [2, 3]
got: [1, 2, 2, 3] expected [1, 2, 3]

我的函数有什么问题?

【问题讨论】:

  • 您的i 既用作nums 列表中的项目,也用作其中的索引...
  • 你不能简单地使用 set???
  • @Hackaholic,OP 正在删除相邻元素而不是删除所有副本

标签: python list python-2.7 list-comprehension


【解决方案1】:

您的代码的问题是您在列表推导表达式中引用的newList 始终与您最初分配的空列表[] 保持一致。表达式[i for i in nums if len(newList) == 0 or nums[i] != newList[-1]]首先使用现有变量计算,然后才将结果分配给newList

换句话说,你的代码相当于

def remove_adjacent(nums):
  newList = []
  otherList = [i for i in nums if len(newList) == 0 or nums[i] != newList[-1]]
  return otherList

您不必使用列表推导来解决这个问题(我个人不会,因为在这种情况下它会变得很棘手)。

【讨论】:

  • 我知道我也不能使用列表推导,实际上作者自己使用result = [] for num in nums: if len(result) == 0 or num != result[-1]: result.append(num) return result
  • @GioacchinoGargiulo,这是正确的,但这是另一个问题。我的帖子是否回答了您最初关于您的代码出了什么问题的问题?
【解决方案2】:
def adj(l):
   if len(l) in {0,1}: # check for empty or list with 1 element
       return l
   return [ele for ind, ele in enumerate(l[:-1]) if ele != l[ind+1]] + [l[-1]]

if ele != l[ind+1]]检查当前元素与列表中下一个索引处的元素,我们转到l[:-1]所以l[ind+1]不会给出索引错误,因此我们需要在最后添加l[-1]结果的元素。

In [44]: l = [1, 2, 2, 3]

In [45]: adj(l)
Out[45]: [1, 2, 3]

In [46]: l = [1, 2, 2, 3,2]

In [47]: adj(l)
Out[47]: [1, 2, 3, 2]

In [48]: l = [2,2,2,2,2]

In [49]: adj(l)
Out[49]: [2]

使用您自己的代码,您将需要一个 for 循环,因为 newList 已分配给列表解析,您没有更新您的原始分配 newList 您已将名称重新分配给列表解析,这是一个全新的对象:

def remove_adjacent(nums):
    if len(l) in {0,1}: # catch empty and single element list
        return l
    newList = [nums[0]] # add first element to avoid index error with `newList[-1]`
    for i in nums[1:]: # start at second element and iterate over the element
        if i != newList[-1]:
            newList.append(i)
    return newList


In [1]: l = [] # assign l to empty list

In [2]: id(l)
Out[2]: 140592635860536 # object id

In [3]: l = [x for x in range(2)] # reassign 

In [4]: id(l)
Out[4]: 140592635862264 # new id new object

【讨论】:

  • 这没有回答问题:我的函数有什么问题?
  • 嗯,这可以解决练习作者的要求,但我仍然不明白为什么我的代码是错误的。
  • @GioacchinoGargiulo:这就是我发布另一个答案的原因。
  • @GioacchinoGargiulo,您正在创建一个列表理解,它是一个新对象,不会修改您首先使用 newList = [] 分配的列表
  • 不用担心,您可以使用列表理解 n0 问题,您在 for 循环中的每次迭代都为 nums[-1] 编制索引,所以 l[ind+1] 也在做同样的事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 2021-09-09
相关资源
最近更新 更多