【发布时间】:2018-04-10 10:02:43
【问题描述】:
我有一个由字母和空格组成的列表:
s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j'];
我需要将其拆分为更小的单独列表:
s=[['a','b'],['b','c'],['d','e','f','g','h'],['i','j']]
我是 python 新手。
整个代码:
#To get the longest alphabetical substring from a given string
s = input("Enter any string: ")
alpha_string = []
for i in range(len(s)-1): #if length is 5: 0,1,2,3
if(s[i] <= s[i+1]):
if i == len(s)-2:
alpha_string.append(s[i])
alpha_string.append(s[i+1])
else:
alpha_string.append(s[i])
if(s[i] > s[i+1] and s[i-1] <= s[i]):
alpha_string.append(s[i])
alpha_string.append(" ")
if(s[i] > s[i+1] and s[i-1] > s[i]):
alpha_string.append(" ")
print(alpha_string)
#Getting the position of each space in the list
position = []
for j in range(len(alpha_string)):
if alpha_string[j] == " ":
position.append([j])
print(position)
#Using the position of each space to create slices into the list
start = 0
final_string = []
for k in range(len(position)):
final_string.append(alpha_string[start:position[k]])
temp = position[k]
start = temp
print(final_string)`
【问题讨论】:
-
刚接触 StackOverflow 和/或编程并不意味着您可以不费吹灰之力就解决问题。至少展示一次尝试,然后我们可以帮助您解决尝试中的问题。
-
很抱歉没有显示努力部分。