我想遍歷 AB 測驗結果并將“文本”串列添加到字典中。
“文本”串列始終是一對 4 個值,從而產生一個包含 8 個或 12 個值的串列。
將生成 100 個這樣的串列。
texts = [
[
'A text',
'89',
'71%',
'10%',
'B text',
'110',
'50%',
'9%',
'C text',
'60'
'30%',
'4%'
],
[
'A text',
'89',
'71%',
'10%',
'B text',
'110',
'50%',
'9%',
]
]
dic = {
'title': '',
'trial': '',
'quality': '',
'ctr': ''
}
for ix in texts:
dic.update(title=ix)
一想到使用更新方法,我的手就停了下來。
dic_list = [
{
'title': 'A text',
'trial': '89',
'quality': '71%',
'ctr': '10%',
}
{
'title': 'B text',
'trial': '110',
'quality': '50%',
'ctr': '9%',
}
]
如何創建上述字典串列?
uj5u.com熱心網友回復:
這是您的輸入資料
texts1 = [
'A text', # 1st element
'89', # 2nd element
'71%', # 3rd element
'10%', # 4th element
'B text', # 1st element
'110', # 2nd element
'50%', # 3rd element
'9%', # 4th element
'C text', # 1st element
'60', # 2nd element
'30%', # 3rd element
'4%' # 4th element
]
這是解決方案
split_lists = [texts1[x:x 4] for x in range(0, len(texts1), 4)]
list_of_dicts = []
temp_dict = {}
for (title, trial, quality, ctr) in split_lists:
temp_dict['title'] = title
temp_dict['trial'] = trial
temp_dict['quality'] = quality
temp_dict['ctr'] = ctr
list_of_dicts.append(temp_dict)
# print(temp_dict)
該串列必須能被 4 整除,因為結果字典中有四個鍵。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/465138.html
下一篇:將串列推導轉換為函式式編程
