在Python中,有没有什么方法可以通过另一个字符串中的空格将字符串拆分成数组?

8zzbczxx  于 2022-12-20  发布在  Python
关注(0)|答案(6)|浏览(118)

我有两个输入字符串。第一个字符串是带空格的单词。第二个字符串是不带空格的相同符号数的单词。任务是将第二个字符串按第一个字符串中的空格拆分成数组。
我试图使它与周期,但有问题的指标超出范围,我找不到其他解决方案。

a = str(input())
b = str(input())
b_word = str()
b_array = list()

for i in range(len(a)):
    if a[i] != " ":
        b_word += b[i]
    else:
        b_array += b_word
        b_word = str()
print(b_array)

输入:

>>head eat
>>aaabbbb

输出:

Traceback (most recent call last):
  File "main.py", line 29, in <module>
    b_word += b[i]
IndexError: string index out of range

预期产出:

>> ["aaab", "bbb"]

先谢了!

ymzxtsji

ymzxtsji1#

a = input()  # you don't need to wrap these in str() since in python3 input always returns a string
b = input()
output = list()

for i in a.split(' '):  # split input a by spaces
    output.append(b[:len(i)])  # split input b
    b = b[len(i):]  # update b

print(output)

输出:

['aaab', 'bbb']
deyfvvtc

deyfvvtc2#

你可以这样做:

a = input()
b = input()

splitted_b = []
idx = 0
for word in a.split():
    w_len = len(word)
    splitted_b.append(b[idx:idx+w_len])
    idx += w_len

print(splitted_b)

其思想是从b中取出a上每个单词长度的连续子串。

dojqjjoe

dojqjjoe3#

您可以不使用索引,而是迭代a的每个字符。如果字符不是空格,请将b的下一个字符添加到b_word。如果是空格,请将b_word添加到b_array

b_iter = iter(b) # Create an iterator from b so we can get the next character when needed

b_word = []
b_array = []

for char in a:
    # If char is a space, and b_word isn't empty, append it to the result
    if char == " " and b_word:
        b_array.append("".join(b_word))
        b_word = []
    else:
        b_word.append(next(b_iter)) # Append the next character from b to b_word

if b_word: # If anything left over in b_word, append it to the result
    b_array.append("".join(b_word))

得到b_array = ['aaab', 'bbb']
注意,我将b_word更改为每次添加字符时.append都会使用的 list,这样可以防止每次添加字符时重新创建整个字符串,然后在添加到b_array之前使用"".join(b_word)连接所有字符。

pvcm50d1

pvcm50d14#

所以为了适应输入中任意数量的空格,它变得有点复杂,因为字母的索引会随着每个空格的增加而改变。所以为了收集字符串中的所有空格,我创建了这个循环,它将考虑多个空格,并随着初始单词中的每个新空格改变索引。

indexs = []
new = ''
for i in range(len(a)):
    if len(indexs) > 0:
        if a[i] == ' ':
            indexs.append(i-len(indexs))
    else:
        if a[i] == ' ':
            indexs.append(i)

然后我们简单地将它们连接在一起,创建一个在预定索引处包含空格的新字符串。

for i in range(len(b)):
    if i in indexs:
        print(i)
        new += " "
        new += b[i]
    else:
        new += b[i]
print(new)

希望这个有用。

ergxz8rk

ergxz8rk5#

代码

sone = input()                 
stwo = 'zzzzzxxxyyyyy'
nwz = []
wrd = ''
cnt = 0
idx = 0

spc = sone.split(' ')      #split by whitespace
a = [len(i) for i in spc]  #list word lengths w/out ws

for i in stwo:
  if cnt == a[idx]:        #if current iter eq. word length w/out ws
    nwz.append(wrd)        #append the word
    wrd = ''               #clear old word
    wrd = wrd + i          #start new word
    idx = idx + 1            
    cnt = 0
    
  else:
    wrd = wrd + i          #building word
  cnt = cnt + 1
    
nwz.append(wrd)            #append remaining word
print(nwz)

结果

>'split and match'
['zzzzz', 'xxx', 'yyyyy']
7kqas0il

7kqas0il6#

考虑基于迭代器和itertools.islice方法的解决方案:

import itertools

def split_by_space(s1, s2):
    chunks = s1.split()
    it = iter(s2)   # second string as iterator
    return [''.join(itertools.islice(it, len(c))) for c in chunks]

print(split_by_space('head eat or', 'aaaabbbcc'))  # ['aaaa', 'bbb', 'cc']

相关问题