list - python - 在列表中,基于字符串添加空格

127 0

我有一个字符串和数组,字符串有与数组相同的字母字符数量,我需要将s拆分为与arr的每个元素相同长度的列表。


s = \'Pythonisanprogramminglanguage\'



arr = [\'lkjhgf\', \'zx\', \'qw\', \'ertyuiopakk\', \'foacdhlc\']




expected == [\'Python\', \'is\', \'an\', \'programming\', \'language\']



时间: 原作者:

100 0

iternext一起使用更简洁:


s = \'Pythonisanprogramminglanguage\'


arr = [\'lkjhgf\', \'zx\', \'qw\', \'ertyuiopakk\', \'foacdhlc\']


new_s = iter(s)


result = [\'\'.join(next(new_s) for _ in i) for i in arr]



输出:


[\'Python\', \'is\', \'an\', \'programming\', \'language\']



原作者:
124 1

一种方法是执行以下操作:


s = \'Pythonisanprogramminglanguage\'



arr = [\'lkjhgf\', \'zx\', \'qw\', \'ertyuiopakk\', \'foacdhlc\']



expected = []


i = 0


for word in arr:


 expected.append(s[i:i+len(word)])


 i+= len(word)



print(expected)



原作者:
121 0

使用简单循环可以按如下方式执行:


s = \'Pythonisanprogramminglanguage\'



arr = [\'lkjhgf\', \'zx\', \'qw\', \'ertyuiopakk\', \'foacdhlc\']



start_index = 0


expected = list()


for a in arr:


 expected.append(s[start_index:start_index+len(a)])


 start_index += len(a)



print(expected)



原作者:
132 2

另一种方法是使用赋值表达式 (在python 3.8中新建):


s = \'Pythonisanprogramminglanguage\' 


arr = [\'lkjhgf\', \'zx\', \'qw\', \'ertyuiopakk\', \'foacdhlc\']



i = 0


expected = [s[i:(i := i+len(word))] for word in arr]



原作者:
142 5

可以使用itertools.accumulate获取要拆分字符串的位置:


>>> s = \'Pythonisanprogramminglanguage\'


>>> arr = [\'lkjhgf\', \'zx\', \'qw\', \'ertyuiopakk\', \'foacdhlc\']


>>> import itertools


>>> L = list(itertools.accumulate(map(len, arr)))


>>> L


[6, 8, 10, 21, 29]



现在,如果你使用自己zip,你将得到间隔:


>>> list(zip([0]+L, L))


[(0, 6), (6, 8), (8, 10), (10, 21), (21, 29)]



你只需使用间隔来拆分字符串:


>>> [s[i:j] for i,j in zip([0]+L, L)]


[\'Python\', \'is\', \'an\', \'programming\', \'language\']



原作者:
87 3

创建一个简单循环,并将单词的长度用作索引:


s = \'Pythonisanprogramminglanguage\' 


arr = [\'lkjhgf\', \'zx\', \'qw\', \'ertyuiopakk\', \'foacdhlc\']



ctr = 0


words = []


for x in arr:


 words.append(s[ctr:len(x) + ctr])


 ctr += len(x)



print(words)



# [\'Python\', \'is\', \'an\', \'programming\', \'language\']



原作者:
57 4

下面是另一种方法:


import numpy as np


ar = [0]+list(map(len, arr))


ar = list(np.cumsum(ar))


output_ = [s[i:ar[ar.index(i)+1]] for i in ar[:-1]]



输出:


[\'Python\', \'is\', \'an\', \'programming\', \'language\']



原作者:
131 1

还有一条路


a,l = 0,[]


for i in map(len,arr):


 l.append(s[a:a+i])


 a+=i


print (l)


#[\'Python\', \'is\', \'an\', \'programming\', \'language\']



原作者:
...