我有一個矩陣(l2)和一個串列(l1)。 我想檢查串列(l1中的元素)中的任何一個字是否在矩陣中。如果有的話,演算法應該把分離出來的詞連接起來。比如說,
l1=['soheila'/span>, 'mahin','rose','pari']
l2=[['so he ila ha','soh e i la h a','so h eil a ha'] 。
['ma h in','m ah in','mahi n'] 。
['r os es', 'ro se s','ros e s'] 。
['pa ri sa','pari s a','p ar i sa'] ]
而我想要的輸出是:
output=[['soheila ha'/span>,'soheila h a'/span>,'soheila ha'/span>]。
['mahin','mahin','mahin'] 。
['roses', 'rose s','rose s'] 。
['pari sa','pari s a','pari sa'] ]
正如你在這個例子中所看到的,矩陣中的字和串列中的字之間的空格被洗掉了,但其余的字沒有。 我使用這段代碼來洗掉矩陣中的所有字符之間的空格:
import numpy.core.defchararray as np_f
l3=list()
l3=l2
new_data = np_f.replace(l3, ' ', ' ')
#print(new_data)。
for count_i, value in enumerate(l2)。
result = [i for i in l3[count_i] and new_data[count_i] if l1[count_i] in i] 。
print(result)
但我不知道如何對問題的條件進行編碼以產生輸出矩陣。我搜索了很多,我知道我可以通過在Java中使用equalsIgnoreCase來實作,但我是Python的初級水平,有弱點。你能幫助我解決這個問題并產生輸出矩陣嗎?
uj5u.com熱心網友回復:
你可以這樣做
l1=['soheila'/span>, 'mahin','rose','pari']
l2=[['so he ila ha','soh e i la h a','so h eil a ha'] 。
['ma h in','m ah in','mahi n'] 。
['r os es', 'ro se s','ros e s'] 。
['pa ri sa','pari s a','p ar i sa'] ]
l = [[ word " " subword.replace(' ', '). replace(word, ' ') for subword in sublist if word in subword。 replace(' ', ') ] for sublist in l2 for wordin l1]
result = list(filter(None, l)
print(result)
輸出:
[['soheila ha', 'soheila ha', 'soheila ha'], ['mahin ', 'mahin ', 'mahin '], ['rose s', 'rose s', 'rose s'], ['pari sa', 'pari sa', 'pari sa']]/p>
uj5u.com熱心網友回復:
如果你不介意我問的話,為什么不直接通過空格來分割L2串列中的每個索引呢:
L3=[] 。
對于i in L2:
L3.append("".join(i .split(" "))
然后正常檢查L1中的作品是否在L3中。
我還沒有檢查過這是否可行,但這是我想到的,是我腦子里的想法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/314494.html
標籤:
下一篇:C 中嵌套If的行為是什么?
