我需要输入一个字符串:“天气今天是”,并得到“天气”,“天气今天”,“天气今天是”的输出。虽然我已经尝试了下面的方法,但是for循环仍然有问题,我非常感谢您的帮助。
我的步骤被分割成一个列表。然后使用for循环插入i,i+1中的单词.命令,直到到达范围的尽头。
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))
输入:今天的天气是“输出:”,“天气”,“今天的天气”,“今天的天气是”
发布于 2019-09-08 12:19:58
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']
发布于 2019-09-08 12:13:53
您逐个迭代字符串列表。在到达的每个项目中,使用切片算子[:]将前面的项目包括到当前位置,这将为您提供所需的子字符串。请参阅下面的片段:
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']
发布于 2019-09-08 12:20:56
你可以加入这样的分裂结果:
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']
不分裂和加入的替代解决方案:
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']
https://stackoverflow.com/questions/57841809
复制相似问题