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

如何将String转换为List/Array?字符串转指定二维列表咨询

Convert String to Nested List of Numbers

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"
  1. Split the string into individual string elements
    Use the split() 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']
    
  2. 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]
    
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:58:34