列表理解不会返回预期的输出

时间:2014-11-07 22:13:40

标签: python list python-2.7 list-comprehension

我正在尝试解决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]

我的功能出了什么问题?

2 个答案:

答案 0 :(得分: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

你不必使用列表理解来解决这个问题(而且我个人不会因为在这种情况下变得棘手)。

答案 1 :(得分:0)

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