本练习取自Google的Python类:
D.给定一个数字列表,返回一个列表,其中所有相邻的==元素已减少为单个元素,因此[1,2,3,3]返回[1,2,3].您可以创建新列表或修改传入列表.
到目前为止,这是我的解决方案:
def remove_adjacent(nums):
if not nums:
return nums
list = [nums[0]]
for num in nums[1:]:
if num != list[-1]:
list.append(num)
return list
Run Code Online (Sandbox Code Playgroud)
但这看起来更像是一个C程序而不是Python脚本,我觉得这可以做得更优雅.
编辑
所以[1, 2, 2, 3]应该给予[1, 2, 3]和[1, 2, 3, 3, 2]应该给予[1, 2, 3, 2]
itertools中有函数可以在这里工作:
import itertools
[key for key,seq in itertools.groupby([1,1,1,2,2,3,4,4])]
Run Code Online (Sandbox Code Playgroud)
你也可以写一个发电机:
def remove_adjacent(items):
# iterate the items
it = iter(items)
# get the first one
last = next(it)
# yield it in any case
yield last
for current in it:
# if the next item is different yield it
if current != last:
yield current
last = current
# else: its a duplicate, do nothing with it
print list(remove_adjacent([1,1,1,2,2,3,4,4]))
Run Code Online (Sandbox Code Playgroud)