3 回答
TA贡献1835条经验 获得超7个赞
尝试这个:
string_to_dict = lambda input_str: {"field1":input_str[:3], "field2":input_str[3:7], "field3":input_str[7:]} string_to_dict("ABCDE12345")
{'field1': 'ABC', 'field2': 'DE12', 'field3': '345'}
速度取决于您的输入源。如果您有 pandas DataFrame,则可以通过使用“map”函数将此函数应用于 Series 来最大化速度:
df['stinrg_series'].map(string_to_dict)
TA贡献1878条经验 获得超4个赞
如果您准备一个数据结构来表示按顺序排列的具有名称和长度的字段,则可以将其应用于字典推导式以将数据拆分为单独的键和值。然后使用json模块转换字典
from itertools import accumulate
import json
structure = [("field1",3),("field2",2),("field3",5)] # define names and lengths
positions = [0,*accumulate(size for _,size in structure)] # computed starting positions
data = "ABCDE12345"
dictdata = { name:data[pos:pos+size] for (name,size),pos in zip(structure,positions) }
jsondata = json.dumps(dictdata)
print(jsondata)
# {"field1": "ABC", "field2": "DE", "field3": "12345"}
TA贡献1998条经验 获得超6个赞
你可以这样做:
function strToObj(str, interface) {
const outObj = {};
let index = 0;
Object.entries(interface).forEach(([key, value]) => {
outObj[key] = str.slice(index, index + value);
index = value
});
return JSON.stringify(outObj);
}
const testStr1 = 'ABCDE12345';
const testInterface1 = {
key1: 3, // 'key1' will become the object key and 3 indicates the number of characters to use for the value
key2: 4,
key3: 3
}
const testStr2 = '+15417543010';
const testInterface2 = {
intlPrefix: 2,
localPrefix: 3,
phonenumber: 7
}
console.log(strToObj(testStr1, testInterface1));
console.log(strToObj(testStr2, testInterface2));
或简化版本,如果您不需要创建可重用的功能
添加回答
举报