如何用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
- 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.
- Join each chunk into a single string: We'll use a separator (like commas) to combine the hashtags in each group. The
csvmodule will automatically handle wrapping these strings in quotes if they contain commas, so you won't get unexpected extra cells. - 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_datalist 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.writertakes 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
相关产品推荐
相关产品推荐

