更清洁/更短的方法来解决这个问题?

hel*_*hod 3 python

本练习取自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]

Joc*_*zel 9

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)

  • 此代码(顶部版本)是OP需要遵循的代码.它并不试图将所有内容强制转换为一个语句,但它简洁明了 - 8行代码(不包括注释,这些注释在教程之外是显而易见的).它还具有在任何迭代器上工作的优点,基于`zip`的解决方案没有; 这个问题实际上并不是必需的,但OP是一个非常有用的属性,OP希望尽快理解.它也可以直接在无限迭代器上运行. (2认同)