在python中,我有一個包含患者資料的元組(很多)串列,如下所示:
lot = [('490001', 'A-ARM1', '1', '2', "a", "b"),
('490001', 'A-ARM2', '3', '4', "c", "d"),
('490002', 'B-ARM3', '5', '6', "e", "f")]
在我的真實資料集中,很多包含 50-150 個元組(取決于患者)。我回圈遍歷每個第二個元組元素,并希望用字典值替換每個“A-”和“B-”字符,因此輸出將變為:
[('490001', 'ZZARM1', '1', '2', 'a', 'b'), ('490001', 'ZZARM2', '3', '4', 'c', 'd'), ('490002', 'XXARM3', '5', '6', 'e', 'f')]
為了滿足這一點,我撰寫了下面的代碼。在這里,我想知道是否有更簡潔(更短)的方式來寫這個。例如,'lot2'。如上所述,該代碼應該最適合大型元組串列。我很想向你學習!
from more_itertools import grouper
dict = {'A-': 'ZZ', 'B-': 'XX'}
for el1, el2, *rest in lot:
for i, j in grouper(el2, 2):
if i j in dict:
lot2 = [ ( tpl[0], (tpl[1].replace(tpl[1][:2], dict[tpl[1][:2]])), tpl[2], tpl[3], tpl[4], tpl[5] ) for tpl in lot]
print(lot2)
uj5u.com熱心網友回復:
如果您正在尋找更短的代碼,這里有一個更短的代碼,沒有使用more_itertools.grouper. 基本上,迭代lot并修改第二個元素(如果需要更改)。請注意,我dict在dct這里命名;dict是內置的 dict 建構式,如果您以后碰巧想使用 dict 建構式,將變數命名為與 Python 內置函式相同會產生問題。
lot2 = []
for el1, el2, *rest in lot:
prefix = el2[:2]
el2 = dct.get(prefix, prefix) el2[2:]
lot2.append((el1, el2, *rest))
可以寫得更簡潔:
lot2 = [(el1, dct.get(el2[:2], el2[:2]) el2[2:], *rest) for el1, el2, *rest in lot]
輸出:
[('490001', 'ZZARM1', '1', '2', 'a', 'b'),
('490001', 'ZZARM2', '3', '4', 'c', 'd'),
('490002', 'XXARM3', '5', '6', 'e', 'f')]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447787.html
標籤:Python python-3.x 列表 字典 更多迭代工具
下一篇:基于字典重命名具有范圍的列
