gpt4 book ai didi

python - 解决此问题的更清洁/更短的方法?

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:39 24 4
gpt4 key购买 nike

此练习摘自 Google's Python Class :

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):
if not nums:
return nums

list = [nums[0]]

for num in nums[1:]:
if num != list[-1]:
list.append(num)

return list

但这看起来更像是一个 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])]

你也可以写一个生成器:

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]))

关于python - 解决此问题的更清洁/更短的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4167009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com