4

以相同长度的字符串和二进制列表为例:

[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
 s  t  a  c  k  o  v  e  r  f  l  o  w

是否有可能获得-t-c-over----如下的新字符串:

[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
 -  t  -  c  -  o  v  e  r  -  -  -  -

也就是说,每个匹配的字符0都将被替换为-. 所需的输出将是如下列表,其中字母匹配1和连字符匹配0分别分组:

['-', 't', '-', 'c', '-', 'over', '----']

谢谢!

4

4 回答 4

4

How about something like this? Zip the two lists and iterate and build the output. Keep the last binary value to determine whether you should append or concat.

blist = [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
string = 'stackoverflow'
output = []    
previous = not blist[0] # to cause the first char to be appended

for b,s in zip(blist, string):
    char = '-' if b == 0 else s

    if previous == b:
        output[-1] += char         
    else:
        output.append(char)

    previous = b

print(output)

Another option is regex:

import re

blist = [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
string = 'stackoverflow'

x = ''.join(['-' if b == 0 else s for b,s in zip(blist, string)])
output = re.findall('(-+|[a-z]+)', x)

print(output)
于 2013-03-02T02:05:31.240 回答
3

您可以享受迭代器的乐趣(无需 zip!:)

it = iter([0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0])
s = 'stackoverflow'

output = [''.join(('-' for i in b) if not a else b)
          for a,b in 
          itertools.groupby(s, key=lambda x: next(it))]

所以输出将是:

['-', 't', '-', 'c', '-', 'over', '----']
于 2013-03-02T02:16:46.790 回答
1

上一个问题答案可能会稍作修改以获得所需的结果

第一个答案:

给定

[''.join(v) for k, v in groupby(st, key = lambda e:next(it_lst))]

修改的

[''.join(v if k else ('-' for _ in v)) 
 for k, v in groupby(st, key = lambda e:next(it_lst))]

第二个答案

给定

[''.join(zip(*v)[-1]) 
 for k, v in groupby(zip(lst, st), key = itemgetter(0)) if k]

修改的

[''.join(zip(*v)[-1] if k else ('-' for _ in v)) 
 for k, v in groupby(zip(lst, st), key = itemgetter(0))]

注意 您需要做的就是

  1. 停止忽略0条目
  2. 对于每个0条目,创建一个长度等于下分组字符串的字符串0
于 2013-03-02T04:04:45.777 回答
1

你可以这样做:

string = "stackoverflow"
arr = [0,1,1,0,1,0,1,0,1,0,0,1,0]
new = ""
for i in range(len(arr)):
    new += string[i]*arr[i] +"-"*(abs(arr[i]-1))

这利用了字符串乘以 0 是一个空字符串。

然后您可以使用正则表达式将其拆分为字符串列表

import re
list = re.findall("-+|[A-z]+", new)

"-+|[A-z]+"匹配长度大于 1 的破折号字符串或长度大于 1 的字母字符串的模式。

于 2013-03-02T05:32:40.870 回答