You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将列表元素转为每行3个单词的单个字符串

问题:将分块后的单词列表转为每行3词的单字符串

核心目标是接收输入文本,输出每行包含3个单词的单字符串,示例如下:

"hello how are,
you, I am
good and you"

目前已编写代码将输入文本处理为每个元素包含3个单词的字符串列表,代码如下:

guion = "The first law of thermodynamics, also known as the law of conservation of energy, states that energy cannot be created or destroyed, only transformed from one form to another. This means that the total amount of energy in a closed system remains constant.In other words, if you take a system and add energy to it, the energy must go somewhere - it can't just disappear. It may be converted into other forms of energy, such as heat or mechanical work, but the total amount of energy in the system will remain the same.This law is important in understanding many processes in physics and engineering, including the behavior of heat engines, the transfer of heat between objects, and the properties of various materials."
new_guion = guion.split()

def separate(lis):
    full = []
    for i in range(0,len(lis),3):
        newelem = lis[i:i + 3]
        full.append(newelem)
        i+=1
    return full

jo = separate(new_guion)

def joinlis(lis):
    unpacked = []
    for i in range(len(lis)):
        almostunpack = " ".join(lis[i])
        unpacked.append(almostunpack)
        i+=1
    return unpacked

unpc = joinlis(jo)
print(unpc)

现在需要将生成的unpc列表整理为每行含3个单词的单个字符串,实现方法如下:

解决方案

直接使用字符串的join()方法,将列表中的每个元素用换行符\n连接,即可得到符合要求的单字符串。如果需要像示例那样给整个字符串包裹双引号,只需在拼接结果前后添加双引号即可。

修改后的代码补充部分:

# 生成每行3词的单字符串
target_str = '\n'.join(unpc)
# 若需要带双引号的输出格式
quoted_target_str = f'"{target_str}"'
# 打印结果
print(quoted_target_str)

说明

  • '\n'.join(unpc)会把列表unpc中的每个3词短语用换行符分隔,拼接成一个连续的字符串,自然实现每行3个单词的格式。
  • 用f-string给拼接后的字符串前后加上双引号,就能完全匹配示例中的输出格式。

内容的提问来源于stack exchange,提问作者Pulsar Plasma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 19:54:57