-
qq_花开花谢_0
尝试这个: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)
-
UYOU
如果您准备一个数据结构来表示按顺序排列的具有名称和长度的字段,则可以将其应用于字典推导式以将数据拆分为单独的键和值。然后使用json模块转换字典from itertools import accumulateimport jsonstructure = [("field1",3),("field2",2),("field3",5)] # define names and lengthspositions = [0,*accumulate(size for _,size in structure)] # computed starting positionsdata = "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"}
-
米琪卡哇伊
你可以这样做: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));或简化版本,如果您不需要创建可重用的功能