我有一个二进制列表,只包含两个元素(如0,1) 1010100010100000000000100000100000101000000000000000100000001000010
如何与事件的自定义设置进行配对转码?
这是编码规则:如果元素连续发生少于3次,则编码为0,
如果元素连续发生4-7次,则编码为1,
如果元素连续发生超过7次,则编码为2。
自定义显示设置:
0-3 :0(短)
4-7 :1(中等)
7:2以上(长)
例如:
如何按照上述规则将01001111000100000000转换为[0,0,1,0,0,0,1,1,1,1,0,0,1,1,0,0,1,0,2]
*a,b
答:0,1(我的列表中只有二进制结果)
B:0,1,2(这是我的自定义频率设置)
发布于 2022-08-31 06:48:42
只有基本语句的解决方案是:
word = '0100111100011100000000'
#Consecutive counts
count=1
counts = []
if len(word)>1:
for i in range(1,len(word)):
if word[i-1]==word[i]:
count+=1
else :
counts.append([ word[i-1],count])
count=1
counts.append([ word[i-1],count])
else:
i=0
counts.append([ word[i-1],count])
#check your conditions
output = []
for l in counts:
if l[1]<= 3 :
output.append([int(l[0]), 0])
elif l[1]> 3 and l[1]<8 :
output.append([int(l[0]), 1])
else:
output.append([int(l[0]), 2])
print(output)
产出:
[[0, 0], [1, 0], [0, 0], [1, 1], [0, 0], [1, 0], [0, 2]]
发布于 2022-08-31 07:16:42
您可以定义一个函数来将组的长度转换为数字,然后使用例如itertools.groupby
来分离不同的字符组,并应用该函数来理解列表。
from itertools import groupby
def f(g):
n = len(list(g))
return 0 if n <= 3 else 1 if n <= 7 else 2
s = "0100111100011100000000"
res = [(int(k), f(g)) for k, g in groupby(s)]
# [(0, 0), (1, 0), (0, 0), (1, 1), (0, 0), (1, 0), (0, 2)]
https://stackoverflow.com/questions/73551659
复制相似问题