例如:string ='AbcDEfGhIJK'
我想使用来获取列表: ['A','bc','DE','f','G','h','IJK']
我正在尝试这样做的逻辑,但到目前为止还算不上运气。
编辑: 我不知道正则表达式,所以我只用了循环 这就是我想出的,虽然它没有给出最后的“ IJK”
u_count = 0
l_count = 0
l_string = ''
u_string = ''
output = []
data = 'AbcDEfGhIJK'
for c in data:
if(c.isupper()):
if(l_count !=0):
output.append(l_string)
l_count = 0
l_string = ''
u_string += c
u_count += 1
if(c.islower()):
if(u_count !=0):
output.append(u_string)
u_count = 0
u_string = ''
l_string +=c
l_count += 1
print(output)
答案 0 :(得分:3)
您可以使用itertools.groupby:
magz = [ 24.638505, 20.446914, 22.10271, 21.227533, 21.761152, 18.923867,
24.054868, 23.92457, 21.515022, 21.835458, 21.204597, 21.848573,
24.036382, 21.126777, 21.599414, 20.044833, 24.390594, 23.772577,
19.608918, 22.676774, 23.6312, 24.12077, 21.22321, 20.350204,
20.548614, 22.650914, 20.561528, 24.892959, 22.49959, 22.94469,
24.346355, 23.934491, 22.448417, 20.535562, 20.785362, 25.131568,
24.462043, 24.173652, 19.105512, 20.641586, 19.5268, 25.0747, 23.254556,
24.460447, 24.37759, 22.708406, 20.765025, 17.27031, 22.723192, 22.4452,
23.366233, 23.238118, 20.72437, 22.278445, 22.231206, 20.98687,
20.341756, 22.968032, 22.504077, 21.277349, 19.163532, 22.44034,
22.406581, 21.999019, 23.313155, 17.945062, 23.027715, 23.640596,
20.60174, 20.124156, 22.39343, 23.786641, 25.201003, 25.227441,
22.537135, 23.779794, 19.416995, 23.550315, 23.225908, 22.579364,
21.69014, 20.50741, 22.543212, 21.640962, 20.425422, 23.793624,
20.554366, 23.522594, 21.03864, 18.282573, 17.33285, 21.015233,
21.611837, 24.00014, 22.741971, 24.416913, 24.053067, 24.314742,
22.400808, 19.622712, 24.911735, 20.04981, 19.128503, 23.83536,
21.864501, 25.037927, 24.449472, 24.200244, 24.492582, 22.378057,
25.411336, 21.727248, 20.16391, 22.045026, 20.017703, 18.534318,
21.995092, 21.434434, 21.825042, 22.78943, 19.006103, 22.398988,
24.198657, 25.018417, 18.829948, 23.94818, 20.813966]
在这里,from itertools import groupby
string = 'AbcDEfGhIJK'
out = [''.join(group) for key, group in groupby(string, key=lambda c: c.islower())]
print(out)
# ['A', 'bc', 'DE', 'f', 'G', 'h', 'IJK']
将为groupby
提供相同输出的字符分组
答案 1 :(得分:0)
您可以使用正则表达式:
import re
text = 'AbcDEfGhIJK'
result = re.split('([a-z]+)', text)
print(result)
输出
['A', 'bc', 'DE', 'f', 'G', 'h', 'IJK']
想法是将字符串拆分为小写字母'([a-z]+)'
,但保持拆分模式。
答案 2 :(得分:0)
str = 'AbcDEfGhIJK'
str=list(str)
for k,v in enumerate(str[:-1]):
joined=''.join([str[k],str[k+1]])
if joined.isupper() or joined.islower():
str[k+1]=joined
str[k]=''
str=[x for x in str if x!='']
print(str)
输出
['A', 'bc', 'DE', 'f', 'G', 'h', 'IJK']