我正在尝试检查python中两个列表的元素,以查看它们在相同位置(索引)中是否包含相同的值。如果假设列表A的位置0中的元素与列表B的位置0中的元素不同,我想从列表A中提取该值并再次开始比较。
我的程序如下:
listA = ["book","2","stage","me","you"]
listB = ["stage","me","you"]
listB始终是listA的子列表!
diff_list = []
for n in range(0, len(listA)):
for k in range(0, len(listB)):
if n == k:
if listA[n] != listB[k]:
rm_item = listA.pop(n)
diff_list.append(rm_item)
k==0
print(k)
在我的终端机中,首先k = 0,然后k =1。是否有办法从listA中删除项目,然后再次开始比较?
感谢您的帮助!说实话...。我想做的就是得到两个字符串之间的区别。我有两个文本,其中文本B始终是文本A的子文本。因此,我使用splitlines()拆分了两个文本,然后比较两个列表以得到所需的文本!
抱歉,但是我是python新手,仍然无法弄清楚有多少事情要做!
所以我有
textA='The first paragraph of the book is written well'
和
textB = 'the book is written well'
结果应该是
text_diff ='the first paragraph of'
python大神给出的解决方案
在我看来,如果您有两个字符串stringA
和stringB
(大概是在\n
上分割的较大文本中的行),使得stringB
始终是stringA
的子字符串,并且您想找到stringA
中多余的内容,那么做类似
stringA = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus aliquam leo odio, ut posuere dui rutrum ac. Nulla facilisi."
stringB = "ut posuere dui rutrum ac"
print stringA.replace(stringB, '')
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus aliquam leo odio, . Nulla facilisi."
编辑:使用更新的OP中的示例文本,您可以执行
textA = 'The first paragraph of the book is written well'
textB = 'the book is written well'
text_diff = textA.lower().replace(textB.lower(), '')
产生
'the first paragraph of'