【问题标题】:How to compare the elements of the list and matrix and eliminate spaces如何比较列表和矩阵的元素并消除空格
【发布时间】:2021-09-13 13:36:53
【问题描述】:

我有一个矩阵(l2)和一个列表(l1)。 我想检查列表中的任何单词(l1 中的元素)是否在矩阵中。如果有,算法应该附加分开的单词。例如,

l1=['soheila','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','soheila h a','soheila ha'],
    ['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 的初学者水平并且有弱点。你能帮我解决这个问题并生成输出矩阵吗?

【问题讨论】:

  • Python 相当于 Java 的 String.equalsIgnoreCase(s1, s2)s1.lower() == s2.lower()
  • 感谢您的帮助。对不起,条件呢?我应该如何通过这段代码比较列表中的字符串和矩阵? @TDk
  • 我的意思是删除矩阵中单词的空格。我解释得很糟糕:)

标签: python python-3.x list if-statement matrix


【解决方案1】:

你可以这样做

l1=['soheila','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 word in 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']]

【讨论】:

  • 哇.. 这么好的解决方案。只有一个元素是不同的,所以我可以在我的程序上工作以产生最好的 l2 矩阵,然后使用你的解决方案来产生输出。十分感谢。这是非常非常有用的。
【解决方案2】:

如果你不介意我问为什么不通过空格分割 L2 列表中的每个索引:

L3=[]
For i in L2:
L3.append("".join(i .split(" ")))

然后正常检查L1中的作品是否在L3中 还没有检查这是否可行,但这是我想到的,我的头顶。

【讨论】:

  • 是的,这是个好问题。谢谢你。如果我只想产生这个输出,我可以像你说的那样编码。但这是程序的一部分,我应该为其编写代码并需要上述输出。
猜你喜欢
  • 2015-06-11
  • 1970-01-01
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 2019-10-08
相关资源
最近更新 更多