给出以下元素列表:
tmp = ['T','h','e','/','*','s','k','y','*','i','s', '/','/','b','l','u','e']
我想:
预期输出:
天空是蓝色的
我的代码工作正常,但是,我想知道是否可以通过更Python的方式来完成它。
for i in range (len(tmp)):
if (tmp[i]=='*' and tmp[i+1]=='*') or (tmp[i]=='*' and tmp[i+1]=='/') or (tmp[i]=='/' and tmp[i+1]=='*') or (tmp[i]=='/' and tmp[i+1]=='/'):
tmp[i+2]=tmp[i+2].upper()
tmp[i]=""
tmp[i+1]=" "
res.append(tmp)
elif (tmp[i]=='*' or tmp[i]=='/'):
tmp[i]=" "
res.append(tmp)
else:
res.append(tmp)
new_sentence = ''.join(res[1])
答案 0 :(得分:0)
您要问的pythonic方法非常简单,只需一行:
tmp = ['a', 'n', '*', '*', ...]
result = "".join(tmp).replace('**', ' ').replace('//', ' ').title().replace('*', ' ').replace('/', ' ').replace(' ', ' ')
根据您需要更换的条件进行多次替换
根据相关更新来编辑答案。为了将*
和/
的出现替换为空格:
import re
tmp_string = "".join(tmp)
result = re.sub(r'[\*|/]{2}', ' ', tmp_string)
result = result.title().replace('*', ' ').replace('/', ' ').replace(' ', ' ')
答案 1 :(得分:0)
您可以将if
简化如下:
forbidden = '*/'
for i in range (len(tmp)):
if tmp[i] and tmp[i+1] in forbidden:
# do what you want
elif tmp[i] in forbidden and tmp[i+1] not in forbidden:
# do what you want
else:
# do what you want