Python 如何对字符串列表执行条件操作,然后返回新列表?

Python 如何对字符串列表执行条件操作,然后返回新列表?,python,for-loop,append,truncate,Python,For Loop,Append,Truncate,我正在编写一个函数,它接受一个列表,每当一个字符串大于m,它就会被截断并追加“…”。这是我到目前为止写的 # example input: words = ['We', 'hold', 'these', 'truths', 'to', 'be', 'self-evident,', 'that', 'all', 'men', 'are', 'created', 'equal,', 'that', 'they', 'are', 'endowed', 'by', 'their', 'Creator',

我正在编写一个函数,它接受一个列表,每当一个字符串大于
m
,它就会被截断并追加
“…”
。这是我到目前为止写的

# example input:
words = ['We', 'hold', 'these', 'truths', 'to', 'be', 'self-evident,', 'that', 'all', 'men', 'are', 'created', 'equal,', 'that', 'they', 'are', 'endowed', 'by', 'their', 'Creator', 'with', 'certain', 'unalienable', 'Rights,', 'that', 'among', 'these', 'are', 'Life,', 'Liberty', 'and', 'the', 'pursuit', 'of', 'Happiness.--That', 'to', 'secure', 'these', 'rights,', 'Governments', 'are', 'instituted', 'among', 'Men,', 'deriving', 'their', 'just', 'powers', 'from', 'the', 'consent', 'of', 'the', 'governed,', '--That', 'whenever', 'any', 'Form', 'of', 'Government', 'becomes', 'destructive', 'of', 'these', 'ends,', 'it', 'is', 'the', 'Right', 'of', 'the', 'People', 'to', 'alter', 'or', 'to', 'abolish', 'it,', 'and', 'to', 'institute', 'new', 'Government,', 'laying', 'its', 'foundation', 'on', 'such', 'principles', 'and', 'organizing', 'its', 'powers', 'in', 'such', 'form,', 'as', 'to', 'them', 'shall', 'seem', 'most', 'likely', 'to', 'effect', 'their', 'Safety', 'and', 'Happiness.', 'Prudence,', 'indeed,', 'will', 'dictate', 'that', 'Governments', 'long', 'established', 'should', 'not', 'be', 'changed', 'for', 'light', 'and', 'transient', 'causes;', 'and', 'accordingly', 'all', 'experience', 'hath', 'shewn,', 'that', 'mankind', 'are', 'more', 'disposed', 'to', 'suffer,', 'while', 'evils', 'are', 'sufferable,', 'than', 'to', 'right', 'themselves', 'by', 'abolishing', 'the', 'forms', 'to', 'which', 'they', 'are', 'accustomed.', 'But', 'when', 'a', 'long', 'train', 'of', 'abuses', 'and', 'usurpations,', 'pursuing', 'invariably', 'the', 'same', 'Object', 'evinces', 'a', 'design', 'to', 'reduce', 'them', 'under', 'absolute', 'Despotism,', 'it', 'is', 'their', 'right,', 'it', 'is', 'their', 'duty,', 'to', 'throw', 'off', 'such', 'Government,', 'and', 'to', 'provide', 'new', 'Guards', 'for', 'their', 'future', 'security.--Such', 'has', 'been', 'the', 'patient', 'sufferance', 'of', 'these', 'Colonies;', 'and', 'such', 'is', 'now', 'the', 'necessity', 'which', 'constrains', 'them', 'to', 'alter', 'their', 'former', 'Systems', 'of', 'Government.', 'The', 'history', 'of', 'the', 'present', 'King', 'of', 'Great', 'Britain', 'is', 'a', 'history', 'of', 'repeated', 'injuries', 'and', 'usurpations,', 'all', 'having', 'in', 'direct', 'object', 'the', 'establishment', 'of', 'an', 'absolute', 'Tyranny', 'over', 'these', 'States.']

M = 5 # desired character limit

count = 0 # setting up counter 

for str in words: # for any strings contained in the "words" list
  
  trunc = str[:M] + "..." # defines truncated string length, appends "..."

  if len(str) > M: # if word length is greater than M
    count += 1 # adds 1 to the counter each loop
    print(trunc) # prints truncated string

  elif len(str) <= M: # if word length is below or equal to M
    print(str) # prints original string

print("Truncated Words:", count) # prints final count
#示例输入:
单词=我们、持有、这些、真理、存在、不言而喻、那、所有、人、是、被创造、平等、那、他们、被赋予、被赋予、被赋予、被赋予、不可剥夺、权利、那、其中、这些、是、生命、自由、追求、幸福“权利”、“政府”、“是”、“建立”、“在”、“人之间”、“派生”、“他们的”、“正义”、“权力”、“来自”、“同意”、“的”、“被治理的”、“无论何时”、“任何形式”、“的”、“政府”、“成为”、“破坏性的”、“这些”、“结束”、“它”、“是”、“权利”、“的”、“人民”、“改变”、“或”、“废除”,‘它’、‘和’、‘到’、‘研究’、‘新的’、‘政府’、‘奠定’、‘基础’、‘基础’、‘这样’、‘原则’、‘组织’、‘它的’、‘权力’、‘在’、‘这样’、‘形式’、‘作为’、‘他们’、‘应该’、‘看起来’、‘最有可能’、‘影响’、‘他们的’、‘安全’、‘幸福’、‘确实’、‘将’、‘命令’、‘那个’、‘政府’“长期的”、“已建立的”、“应该的”、“不”、“被”、“改变的”、“为”、“光的”、“暂时的”、“原因的”、“相应的”、“所有的”、“经验的”、“已经的”、“展示的”、“那”、“人类的”、“更多的”、“倾向的”、“忍受的”、“而”、“邪恶的”、“是”、“可忍受的”、“比的”、“对的”、“他们自己的”、“废除的”、“形式的”、“到的”,“哪一个”、“他们”、“是”、“习惯的”、“但是”、“何时”、“一个”、“长”、“火车”、“的”、“滥用”、“和”、“篡夺”、“追求”、“不变”、“相同”、“对象”、“证据”、“设计”、“减少”、“他们”、“在”、“绝对”、“专制”、“它”、“是”、“他们的”、“权利”、“它”、“是”、“他们的”、“责任”、“去”、“扔掉”、“这样的”、“政府”“国家”、“政府”、“提供”、“新的”、“警卫”、“为”、“他们的”、“未来”、“安全。”——“这样”、“已经”、“过去”、“病人”、“容忍”、“这些”、“殖民地”、“和”、“这样”、“现在”、“必要性”、“约束”、“他们”、“改变”、“他们的”、“以前的”、“系统”、“政府的”、“历史”、“公共关系”、“公共关系”“目前”、“国王”、“英国”、“is”、“a”、“历史”、“of”、“重复”、“伤害”、“篡夺”、“所有”、“拥有”、“在”、“直接”、“客体”、“建立”、“安”、“绝对”、“暴政”、“超过”、“这些”、“国家”。]
M=5#所需字符限制
计数=0#设置计数器
对于单词中的str:#对于“单词”列表中包含的任何字符串
trunc=str[:M]+“…”#定义截断的字符串长度,并附加“…”
如果len(str)>M:#如果字长大于M
count+=1#每个循环向计数器添加1
打印(trunc)#打印截断的字符串

elif len(str)如果您想获得所有被截断单词的列表,我建议:

(一) 设置一个空列表以保存修改的单词(保持不变的单词+截断的单词)。将其放置在for循环的开头和外部

trunc_words=[]
  • 保持for/if/elif循环不变(我建议这样做,这样您就可以保持代码结构不变,因为这可能会帮助您更好地遵循答案)。 现在,您需要通过添加以下内容,将输入if和elif条件的单词添加到新列表(trunc_单词列表)中:

    如果,则在中添加截断的单词:

    trunc_words.append(trunc)
    
    将输入for循环的实际单词附加到elif

    trunc_words.append(i)
    
    基本上,您的整个代码都是这样的(虽然缩短了原始单词列表,但我使用“I”而不是“str”,因为您不应该使用保留字来定义变量/计数器):

    #示例输入:
    单词=[“我们”、“持有”、“这些”、“真理”、“存在”、“不言而喻”、“那”、“所有”、“人”、“都是”、“被创造的”、“平等的”、“那”、“他们”、“是”、“被赋予的”、“他们的”、“创造者”、“有着”]
    trunc_words=[]
    M=5#所需字符限制
    计数=0#设置计数器
    对于文字中的i:#对于“文字”列表中包含的任何字符串
    trunc=i[:M]+“…”#定义截断的字符串长度,并附加“…”
    如果len(i)>M:#如果字长大于M
    count+=1#每个循环向计数器添加1
    trunc_words.append(trunc)
    打印(trunc)#打印截断的字符串
    
    elif len(i)列表中变量的语法
    不允许就地修改。您可以使用
    enumerate
    修改列表(但字符串是不可变的,因此将再次创建它们,旧的将稍后使用垃圾收集器处理)

    或创建具有列表理解功能的新列表:

    trunc_words = [s[:min(len(s),M)] + ('...' if len(s)>M else '') for s in words]
    

    请避免使用内置名称作为变量。
    str
    是一种类型,而code,其中
    len(str)
    被调用时,总是会让读者感到惊讶。

    您已经尝试了什么?尝试时发生了什么?不适合问我们特定的编码序列是否能满足您的要求:您拥有摆在您面前的最终权限--Python解释器。我相信您在回答中已经具备了所有需要的部分,但是当您尝试您建议的内容时,会发生什么情况?它只会返回列表中的最后一个字符串。我假设这是因为“str”仅是最新值的占位符。因此,我的问题是是否可以继续使用“str in words:”,或者我的问题是尝试从函数内部追加str&trunc
    for i, s in enumerate(words):
        words[i] = s[:min(len(s),M)] + ('...' if len(s)>M else '')
    
    trunc_words = [s[:min(len(s),M)] + ('...' if len(s)>M else '') for s in words]