iT邦幫忙

0

顯示出重複字串

不明 2022-09-23 14:08:18672 瀏覽
  • 分享至 

  • xImage

大家好,我想請問
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}

不過這個只能跑單維的,如果變成多維就會跳錯誤
請問大家有比較好的解決辦法嗎?希望大家能幫幫忙

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
hokou
iT邦好手 1 級 ‧ 2022-09-23 14:39:44
最佳解答

基本上是在原本的外面多加一層

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}]
不明 檢舉

太好了!真的太感謝了!!

0
froce
iT邦大師 1 級 ‧ 2022-09-23 14:36:34

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)
不明 檢舉

謝謝!!!

我要發表回答

立即登入回答