编辑 python 列表



我想做什么?

我想创建一个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]

谁能建议我能做些什么来实现第 (3( 部分?提前感谢!

使用列表推导

>>> 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', 'daptedaxy', 'piritssxy', 'set', 'ressed.pxy', 'up', 'to']

你可以执行以下操作:

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)]   

对于任何这样的词:t = 'request'您可以使用切片:

t[1:]+t[0]+'xy'

最新更新