如何用Python去重连续的数字
我在找一些代码来用Python实现以下功能(如果能用Snowflake解决方案也可以)。
column A (before transformation)
8->8->8->8->5->7
8->5->5->5->7->8->7->7
25->15->15->13->18
25->15->15->13->18->15
需要去掉重复的数字,同时保持它们的顺序。只有当这些数字是相邻的时候,才算重复。
column A (after transformation)
8->5->7
8->5->7->8->7
25->15->13->18->15
谢谢!
我不知道该怎么做。
1 个回答
0
你可以通过将每个项目添加到一个新列表中,前提是它和之前的项目不一样,来去掉连续的重复项。或者,正如@juanpa.arrivillag在评论中提到的,你也可以使用itertools
,这样可以用一行代码就完成这个操作。
这里有个例子:
# Copied from the examples in the question
a = [
[8, 8, 8, 8, 5, 7],
[8, 5, 5, 5, 7, 8, 7, 7],
[25, 15, 15, 13, 18],
[25, 15, 15, 13, 18, 15]
]
# create a new output list
b = []
# Process each list in a
for sublist in a:
# Create an output to hold the new, reduced list
b.append([])
for item in sublist:
# If this list is empty (first item) or if it's a new item, add it
if not len(b[-1]) or b[-1][-1] != item:
b[-1].append(item)
# Print the results to the terminal
for sublistb in b:
print(sublistb)
print()
# As suggested by @juanpa.arrivillag
import itertools
c = [[item for item, _ in itertools.groupby(sublist)] for sublist in a]
for sublistc in c:
print(sublistc)
print(f'Same: {c == b}')
当我运行这个代码时,得到的输出是:
[8, 5, 7]
[8, 5, 7, 8, 7]
[25, 15, 13, 18]
[25, 15, 13, 18, 15]
[8, 5, 7]
[8, 5, 7, 8, 7]
[25, 15, 13, 18]
[25, 15, 13, 18, 15]
Same: True
如果你有任何问题,随时告诉我。
编辑:
我添加了itertools
的一行代码。
感谢@juanpa.arrivillag提供的这个很棒的一行代码。