如題
我有三個list of list
一個list_tmp打算當作標籤用
list_tmp=['A','B','C','D','E','F','G']
a=[['A','1'],['B','2'],['C','3']]
b=[['A','5'],['C','2'],['D','1']]
c=[['C','1'],['E','2']]
我有嘗試過將有值得加進來
但是格式上會偏掉
我期望的結果是
如果a裡面有A則加入1 b裡面有A則加入5 c裡面沒有A則加入'-'
都沒有的話就比如F跟G就加入'-'
list_tmp2=[['A','1','5','-']
['B','2','-','-']
['C','3','2','1']
['D','-','1','-']
['E','-','-','2']
['F','-','-','-']
['G','-','-','-']]
求救大神 感謝
最基本的巢狀迴圈
def main():
list_tmp = ['A','B','C','D','E','F','G']
a = [['A','1'],['B','2'],['C','3']]
b = [['A','5'],['C','2'],['D','1']]
c = [['C','1'],['E','2']]
list_holder = [a, b, c]
list_tmp2 = []
for x in list_tmp:
spec = [x]
for y in list_holder:
spec.append(checker(y, x))
list_tmp2.append(spec)
print(list_tmp2)
def checker(arr, eng):
for x in arr:
if x[0] == eng:
return x[1]
return '-'
main()
list_tmp = ["A", "B", "C", "D", "E", "F", "G"]
a = [["A", "1"], ["B", "2"], ["C", "3"]]
b = [["A", "5"], ["C", "2"], ["D", "1"]]
c = [["C", "1"], ["E", "2"]]
targets = [a, b, c]
list_tmp2 = [[i] + [t[keys.index(i)][1] if i in (keys := [v[0] for v in t]) else "-" for t in targets] for i in list_tmp]
print(list_tmp2)
這樣算 one-liner 嗎
不過因為有用到賦值表達式的關係,所以需要 python 3.8 以上
假設標籤的字母是唯一。那得用 set。
資料的部份,如果要確保標籤是唯一,那得用 dict。
labels = set(['A', 'B', 'C', 'D', 'E', 'F'])
data_a = [['A','1'],['B','2'],['C','3']]
data_b = [['A','5'],['C','2'],['D','1']]
data_c = [['C','1'],['E','2']]
dicts = [dict(x) for x in [data_a, data_b, data_c]]
{l: [d.get(l) or '-' for d in dicts] for l in labels}
如果轉成 DataFrame,那用 merge 就可以搞定了。只是就得載入套件了。