我想做什么?
我想要创建一个python程序,它接受一个文本文件,将文本变成一个字符串列表,如下所示
['Man', 'request', 'adapted', 'spirits', 'set', 'pressed.', 'Up', 'to'] (1)
,将每个单词的字母数输入如下不同的列表
[3, 7, 7, 7, 3, 8, 2, 2](2)
并检查如果每个字符串元素的数目大于3 (>3),则移除其第一个字母,并将其添加到单词的末尾,并加上'xy‘字符串。最后清单的结果应是:
['Man', 'equestrxy', 'daptedaxy', 'piritssxy', 'set', 'ressed.pxy', 'Up', 'to'](3)
我已经做了什么?我已经将(1)和(2)作为代码的一部分,我目前正在尝试(3)。
我的代码有注释:
text = open("RandomTextFile.txt").read().split() #this is the the part (1) #function that creates the second part (2)def map_(A): return list(map(len, A)) words = map_(text) #list that contains the example list of (2)
#This is the part (3) and I try to achieve it by creating a loop
for i in range(y):
if words[i]>3:
text[i] = [x + string for x in text]有人能建议我能做些什么来达到这个目的吗?提前感谢!
发布于 2020-01-13 23:04:17
使用列表组合
>>> x = ['Man', 'request', 'adapted', 'spirits', 'set', 'pressed.', 'Up', 'to']
>>> [i[1:] + i[0] + 'xy' if len(i) > 3 else i for i in x]'Man','equestrxy',‘dapted西’,'piritssxy','set','ressed.pxy','Up',‘
’
发布于 2020-01-13 23:03:51
你可以这样做:
def format_strings(strs):
len_strs = [len(s) for s in strs]
return [strs[i][1:] + 'xy' if len_str > 3
else strs[i] for i, len_str in enumerate(len_strs)] 发布于 2020-01-13 23:14:30
对于任何像这样的词:t = 'request',您可以使用切片:
t[1:]+t[0]+'xy'https://stackoverflow.com/questions/59725389
复制相似问题