如何将String转换为List/Array?字符串转指定二维列表咨询
Got it, let's break down how to turn your string into the nested list you need. Here's a straightforward approach in Python:
Step-by-Step Solution
First, let's start with your original string:
a = "38 186 298 345 0.93345 27 198 277 389 0.86006 33 127 293 354 0.89782"
Split the string into individual string elements
Use thesplit()method to break the string at spaces. This gives us a flat list of string representations of numbers:str_elements = a.split() # Result: ['38', '186', '298', '345', '0.93345', '27', '198', '277', '389', '0.86006', '33', '127', '293', '354', '0.89782']Convert each string to the appropriate numeric type
We need to turn strings into integers or floats. A simple helper function can handle this:def str_to_num(s): num = float(s) # If the number is a whole number, convert to int; keep as float otherwise return int(num) if num.is_integer() else num numeric_elements = [str_to_num(elem) for elem in str_elements] # Result: [38, 186, 298, 345, 0.93345, 27, 198, 277, 389, 0.86006, 33, 127, 293, 354, 0.89782]Group elements into sublists of 5
Use a list comprehension with a step size of 5 to slice the flat list into chunks of 5 elements each:b = [numeric_elements[i:i+5] for i in range(0, len(numeric_elements), 5)]
Full Combined Code
You can also combine these steps into a concise one-liner (though the step-by-step is more readable):
a = "38 186 298 345 0.93345 27 198 277 389 0.86006 33 127 293 354 0.89782" def str_to_num(s): num = float(s) return int(num) if num.is_integer() else num b = [list(map(str_to_num, a.split()[i:i+5])) for i in range(0, len(a.split()), 5)] # Print the result to verify print(b) # Output: [[38, 186, 298, 345, 0.93345], [27, 198, 277, 389, 0.86006], [33, 127, 293, 354, 0.89782]]
This will give you exactly the nested list format you're looking for. The helper function ensures that whole numbers are stored as integers (matching your target b), while decimal numbers stay as floats.
内容的提问来源于stack exchange,提问作者AjItH HeGdE

