如何将f.readlines()获取的多行列表转换为3列array数组?
Got it, let's turn that list of strings into a proper 3-column array. Here are two straightforward ways to do this in Python—one using pure Python (no extra libraries) and another using NumPy, which is ideal for numerical work later on.
Pure Python Approach (No External Libraries)
Each string in your list has commas separating values, plus a trailing comma and newline character. We'll clean each line, split into values, convert to numbers, then build our 3-column structure:
# Your original data list data = ['0, 0, 0.16548735788092,\n', '1, 3.90625E-05, 0.368149412097409,\n', '2, 7.8125E-05, 0.184674297925085,\n', '3, 0.0001171875, 0.00359755125828087,\n', '4, 0.00015625, 0.0131910212803632,\n', '5, 0.0001953125, 0.24703185306862,\n', '6, 0.000234375, 0.474876766093075,\n'] # Process each line to clean and convert values processed_data = [] for line in data: # Remove newline characters and split the string by commas elements = line.strip().split(',') # Filter out empty strings (from trailing commas) and trim whitespace from each value cleaned_elements = [elem.strip() for elem in elements if elem.strip()] # Convert to numeric types: first column as integer, others as float row = [int(cleaned_elements[0]), float(cleaned_elements[1]), float(cleaned_elements[2])] processed_data.append(row) # Now processed_data is a list of lists with 3 columns print(processed_data)
NumPy Approach (For Numerical Operations)
If you plan to do calculations, statistics, or other numerical tasks with this array, NumPy is far more efficient. Here's how to convert your list to a NumPy array:
import numpy as np # Reuse your original data list data = ['0, 0, 0.16548735788092,\n', '1, 3.90625E-05, 0.368149412097409,\n', '2, 7.8125E-05, 0.184674297925085,\n', '3, 0.0001171875, 0.00359755125828087,\n', '4, 0.00015625, 0.0131910212803632,\n', '5, 0.0001953125, 0.24703185306862,\n', '6, 0.000234375, 0.474876766093075,\n'] # Process each line into a list of floats numeric_rows = [] for line in data: parts = line.strip().split(',') # Filter empty entries and convert all values to float (NumPy handles integers as floats seamlessly) nums = [float(p.strip()) for p in parts if p.strip()] numeric_rows.append(nums) # Convert to a NumPy array result_array = np.array(numeric_rows) # Verify the shape (should be (7,3) for 7 rows and 3 columns) print(result_array.shape) print(result_array)
Both methods will give you a valid 3-column structure. The pure Python version is great if you want to avoid external dependencies, while NumPy is the go-to choice for any heavy numerical work.
内容的提问来源于stack exchange,提问作者JPV

