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

如何用Python将列表内容按5词/单元格写入CSV单行?

Hey there! Let's get this sorted for you. The core idea here is to split your original hashtag list into groups of 5 first, then turn each group into a single string (so they fit into one CSV cell), and finally write all those grouped strings as a single row in your CSV. Also, don't forget we need to import the csv module—your original code was missing that, which would throw an error.

Step-by-Step Solution

  1. Chunk the list into groups of 5: Use a list comprehension to slice your original list into smaller groups, each containing up to 5 elements. This works even if the final group has fewer than 5 items.
  2. Join each chunk into a single string: We'll use a separator (like commas) to combine the hashtags in each group. The csv module will automatically handle wrapping these strings in quotes if they contain commas, so you won't get unexpected extra cells.
  3. Write the chunks as one row: Instead of writing each hashtag as a separate cell, we'll pass our list of chunked strings to writerow() to put everything in a single row.

Corrected Code Example

import csv

dataList = ['#cyclone', '#twister', '#thunderstorm', '#supercell', '#wind', 
            '#weatherradar', '#storm', '#waterspout', '#tropicalcyclone', '#hurricane', 
            '#typhoon', '#snowstorm']

# Split the list into chunks of 5 elements
chunk_size = 5
chunked_data = [', '.join(dataList[i:i+chunk_size]) for i in range(0, len(dataList), chunk_size)]

# Write the chunked data to CSV as a single row
with open('test.csv', 'w', encoding='utf-8', newline='') as fp:
    writer = csv.writer(fp, delimiter=',')
    writer.writerow(chunked_data)

What This Does

  • The chunked_data list will end up looking like this:
    [
        '#cyclone, #twister, #thunderstorm, #supercell, #wind',
        '#weatherradar, #storm, #waterspout, #tropicalcyclone, #hurricane',
        '#typhoon, #snowstorm'
    ]
    
  • When written to CSV, each of these strings becomes its own cell in the same row. The csv.writer takes care of quoting cells with commas, so your CSV stays properly formatted.

If you'd prefer a different separator inside the cells (like spaces instead of commas), just swap ', ' with ' ' in the join() call.

内容的提问来源于stack exchange,提问作者Muhammad Hamaad Latif

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:23:47