如何在列表中插入多个值?(Python)

2024-04-25 18:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我想为列表中的每个字符串添加一个空格。结果与字符串或列表无关。但是我想得到字符串中可以有空格的所有情况的数目。你知道吗

首先,我试着这样做,使字符串列表。你知道吗

sent = 'apple is good for health'
sent.split(' ')
sentence = []
b = ''

for i in sent:
    c = ''
    for j in sent[(sent.index(i)):]:
        c += j
    sentence.append((b+' '+c).strip())
    b += i

sentence

在这种情况下,结果将获得仅包含一个空格的字符串。你知道吗

我也试过了

for i in range(len(sent)):
     sent[i:i] = [' ']

另一个尝试是' '.join(sent[i:]) 但结果是一样的。你知道吗

我怎样才能得到 'apple isgoodforhealth', 'appleis goodforhealth', 'appleisgood forhealth', 'appleisgoodfor health', 'appleis goodfor health', 'apple isgood forhealth', 'appleisgood forhealth' ... 这样地?你知道吗

我真的想得到所有病例的数目。你知道吗


Tags: 字符串inapple列表foris情况sentence
2条回答

使用加入:-

sent = 'apple is good for health'                 
sent = sent.split(' ')             
start_index = 0
last_index = len(sent)
for i in range(len(sent)-1):       
    first_word = "".join(sent[start_index:i+1])   
    second_word = "".join(sent[i+1:last_index])
    print(first_word, " ", second_word)

Hope the above code will give output your way i.e, 'apple isgoodforhealth', 'appleis goodforhealth', 'appleisgood forhealth etc.

我对这个问题的看法是利用itertools.combinations。你知道吗

import itertools

sent = 'apple is good for health'
sent = sent.split(' ')

# Get indices for spaces
N = range(len(sent) - 1)

for i in N:
    # Get all combinations where the space suits
    # Note that this doesn't include the option of no spaces at all
    for comb in itertools.combinations(N, i + 1):
        # Add space to the end of each word
        # with index contained in the combination 
        listsent = [s + " " if j in comb else s for j, s in enumerate(sent)]
        # Make the result a string or count the combinations if you like
        tempsent = "".join(listsent)
        print(tempsent)

相关问题 更多 >

    热门问题