我有一個清單:
groups = ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D']
我需要映射每個值以獲得這樣的輸出,獨立于內部組和元素的數量:
[0,0,0,1,1,0,0,1]
每次組更改時,輸出中的值都應切換。
uj5u.com熱心網友回復:
使用Python
使用串列理解和 python 3.8 的海象運算子:
groups = ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D']
flag = 0
out = [flag if a==b else (flag:=1-flag) for a, b in zip(groups, groups[:1] groups)]
或者itertools:
from itertools import groupby, chain
out = list(chain.from_iterable([i%2]*len(list(g))
for i, (_, g) in enumerate(groupby(groups))))
輸出:
[0, 0, 0, 1, 1, 0, 0, 1]
使用熊貓:
import pandas as pd
out = pd.factorize(groups)[0]%2
輸出:
array([0, 0, 0, 1, 1, 0, 0, 1])
或者:
s = pd.Series(groups)
out = (s.ne(s.shift(fill_value=s[0]))
.cumsum().mod(2).tolist()
)
輸出:
[0, 0, 0, 1, 1, 0, 0, 1]
使用麻木的:
import numpy as np
out = np.cumsum(groups != np.r_[groups[:1], groups[:-1]])%2
輸出:
array([0, 0, 0, 1, 1, 0, 0, 1])
uj5u.com熱心網友回復:
這是另一個 O(n) 解決方案:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/530644.html
上一篇:從物件mongodb聚合的嵌套陣列中僅過濾需要的物件
下一篇:python和計算數字的冪
