首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在字符串输入之间加上空格的单字列表

在字符串输入之间加上空格的单字列表
EN

Stack Overflow用户
提问于 2019-09-08 12:06:42
回答 3查看 43关注 0票数 0

我需要输入一个字符串:“天气今天是”,并得到“天气”,“天气今天”,“天气今天是”的输出。虽然我已经尝试了下面的方法,但是for循环仍然有问题,我非常感谢您的帮助。

我的步骤被分割成一个列表。然后使用for循环插入i,i+1中的单词.命令,直到到达范围的尽头。

代码语言:javascript
运行
复制
def test(data):
    splitString = data.split()
    result = {}

    for i in range(len(splitString)):
        if i != max(range(len(splitString))):
            result.append(i)
            i + 1
    return result


s = "The weather today is"
print(test(s))

输入:今天的天气是“输出:”,“天气”,“今天的天气”,“今天的天气是”

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-09-08 12:19:58

代码语言:javascript
运行
复制
def test(data):
  # Form words
  words = data.split()

  # Use list comprehension to generate
  # words[:i] are sub list of words from zero to index i
  # we join this sublist into a string
  return [" ".join(words[:i]) for i in range(1, len(words)+1)]

t = "The weather today is"
print(test(t)) # ['The', 'The weather', 'The weather today', 'The weather today is']
票数 0
EN

Stack Overflow用户

发布于 2019-09-08 12:13:53

您逐个迭代字符串列表。在到达的每个项目中,使用切片算子[:]将前面的项目包括到当前位置,这将为您提供所需的子字符串。请参阅下面的片段:

代码语言:javascript
运行
复制
a = ["the", "weather", "today", "is", "bad"]
for i in range(len(a)):
   print(a[:i])  # slice till the current element

[]
['the']
['the', 'weather']
['the', 'weather', 'today']
['the', 'weather', 'today', 'is']
票数 1
EN

Stack Overflow用户

发布于 2019-09-08 12:20:56

你可以加入这样的分裂结果:

代码语言:javascript
运行
复制
def test(data):
    splitted = data.split()
    return [
        ' '.join(splitted[:i])
        for i in range(1, len(splitted) + 1)
    ]

test('The weather today is')
# ['The', 'The weather', 'The weather today', 'The weather today is']

不分裂和加入的替代解决方案:

代码语言:javascript
运行
复制
def test(data):
    def iter_values():
        for idx, character in enumerate(data):
            if character == ' ':
                yield data[:idx]
        yield data
    return list(iter_values())

test('The weather today is')
# ['The', 'The weather', 'The weather today', 'The weather today is']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57841809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档