如何在Python 3中从CSV文件创建自定义列表?
Convert CSV Data to Target List Format
If you need to transform your CSV data into the space-separated list format you specified, here's a straightforward Python solution that reads the CSV and constructs the exact output you want:
Step-by-Step Explanation:
- Use Python's built-in
csvmodule to parse the CSV file (no external libraries required). - Skip the header row since we don't need the column labels in our final output.
- For each data row, extract the
Date,P_Sales_Qty, andCategoryvalues, adding each one to a single list. - Join all collected values with spaces, then wrap the result in square brackets to match your desired format.
Python Code:
import csv # Initialize an empty list to collect all values output_values = [] # Replace 'your_csv_file.csv' with the actual path to your CSV file with open('your_csv_file.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) # Skip the header row next(csv_reader) for row in csv_reader: # Extract the three required columns (indices 1, 2, 3) output_values.append(row[1]) output_values.append(row[2]) output_values.append(row[3]) # Format into the desired string final_output = f"[{ ' '.join(output_values) }]" print(final_output)
Expected Output:
[2016-03-20 1 17 2016-03-23 1 17 2016-03-25 2 17 2016-03-31 2 17 2016-04-02 3 17 2016-04-04 1 17 2016-04-09 1 17 2016-04-10 1 17 2016-04-28 1 17 2016-04-29 2 17 2016-04-30 1 17]
This code will work perfectly with the CSV data you provided. Just make sure to update the filename in the open() function to match your actual file path.
内容的提问来源于stack exchange,提问作者Sai
相关产品推荐
相关产品推荐

