【问题标题】:Editing a python list编辑 python 列表
【发布时间】:2020-01-13 22:56:20
【问题描述】:

我想做什么?

我想创建一个 python 程序,它接受一个文本文件,将文本变成这样的字符串列表
@987654321 @ (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)

我的 cmets 代码:

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) 部分?提前致谢!

【问题讨论】:

    标签: python arrays string list split


    【解决方案1】:

    使用列表理解

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

    【讨论】:

    • 感谢它也可以工作,而且它是一个更快的“时间”解决方案!
    【解决方案2】:

    你可以这样做:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 正如我所检查的,切片是回答我的问题的最佳方法!谢谢。
      猜你喜欢
      • 1970-01-01
      • 2019-01-09
      • 2017-04-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      相关资源
      最近更新 更多