def value_switcher(groups):
if not groups:
return groups
new_groups = [0]
for i in range(1, len(groups)):
if groups[i-1] != groups[i]:
if new_groups[i-1] == 0:
new_groups.append(1)
else:
new_groups.append(0)
else:
new_groups.append(new_groups[i-1])
return new_groups
我对它进行了如下测试:
groups = ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D']
assert value_switcher(groups) == [0, 0, 0, 1, 1, 0, 0, 1]
groups = ['A']
assert value_switcher(groups) == [0]
groups = ['B', 'A', 'B', 'B', 'A']
assert value_switcher(groups) == [0, 1, 0, 0, 1]
groups = []
assert value_switcher(groups) == []
groups = None
assert value_switcher(groups) is None
2条答案
按热度按时间yptwkmov1#
使用python
使用列表理解和Python3.8+的海象运算符:
或
itertools
:产出:
使用pandas:
产出:
或者:
产出:
使用numpy:
产出:
svmlkihl2#
这里有另一个O(N)解决方案:
我对它进行了如下测试: