3 回答

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
嘗試這個(gè):
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”函數(shù)將此函數(shù)應(yīng)用于 Series 來最大化速度:
df['stinrg_series'].map(string_to_dict)

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果您準(zhǔn)備一個(gè)數(shù)據(jù)結(jié)構(gòu)來表示按順序排列的具有名稱和長(zhǎng)度的字段,則可以將其應(yīng)用于字典推導(dǎo)式以將數(shù)據(jù)拆分為單獨(dú)的鍵和值。然后使用json模塊轉(zhuǎn)換字典
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貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
你可以這樣做:
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));
或簡(jiǎn)化版本,如果您不需要?jiǎng)?chuàng)建可重用的功能
添加回答
舉報(bào)