大家好,我想請問
a=[['a','a','b','b','c','c','g'], ['a','b','c','c']]
b=['a','c','g']
希望找出a中包含b字元的部分
能得出[['a','a','c','c','g'], ['a','c','c']]這樣的結果
可是怎麼試結果都是[['a','c','g'], ['a','c']]這樣的答案
請問結果有辦法顯示重複字元嗎?
後續再計算多維列表中每一列表字元出現的次數
lists = ['a','a','b','b','c','c','c']
f1 = dict()
for i in lists:
    if i in f1:
        f1[i] += 1
    else:
        f1[i] = 1
print(f1)
{'a': 2, 'b': 2, 'c': 3}
不過這個只能跑單維的,如果變成多維就會跳錯誤
請問大家有比較好的解決辦法嗎?希望大家能幫幫忙
基本上是在原本的外面多加一層
a=[['a','a','b','b','c','c','g'], ['a','b','c','c']]
b=['a','c','g']
output1 = []
output2 = []
for lists in a:
    temp = []
    f1 = dict()
    for i in lists:
        if i in b:
            temp.append(i)
            if i in f1:
                f1[i] += 1
            else:
                f1[i] = 1
    output1.append(temp)
    output2.append(f1)
print(output1)
print(output2)
# [['a', 'a', 'c', 'c', 'g'], ['a', 'c', 'c']]
# [{'a': 2, 'c': 2, 'g': 1}, {'a': 1, 'c': 2}]
a=[['a','a','b','b','c','c','g'], ['a','b','c','c']]
b=['a','c','g']
result = []
for item in a:
    result.append(list(filter(lambda x: x in b, item)))
    
print(result)
# 計算次數
from collections import Counter
counterResult = []
for item in result:
    counterResult.append(Counter(item))
    
print(counterResult)