【发布时间】: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