我正在尝试检查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'
答案 0 :(得分:4)
在我看来,如果您有两个字符串stringA
和stringB
(可能是来自\n
上较大文本的行,则stringB
始终是子字符串stringA
的{{1}},你想在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'
答案 1 :(得分:1)
尝试zip
>>> listA = ['Caesar', 'Pompey', 'Krassus']
>>> listB = ['Augustus', 'Pompey']
>>> for x,y in zip(listA, listB):
print(x == y)
如果你想让listA中的所有值都不在listB中,那么顺序很重要。
a_unique = [x[0] for x in zip(listA, listB) if x[0] != x[1]]
答案 2 :(得分:0)
如果订单不重要且您想查看两个列表的设置差异,可以使用:
print(list(set(listA) - set(listB)))
输出:
['2', 'book']
答案 3 :(得分:0)
假设子列表B与列表A的顺序相同,您可以这样做:
listA = ["blabla", "book", "2", "stage", "me", "you"]
listB = ["stage", "me", "you"]
for i in range(len(listB)):
if listA[i] != listB[i]:
del listA[0]
print listA
你并不需要有一个diff_list,在结尾列表A将与列表B相同。
答案 4 :(得分:0)
您可以使用remove删除列表中的元素。 如果不存在,请使用try块。 while循环是在listA中查找重复项。 由于问题已经澄清,以找到A中不在B中的元素,我已对此进行了修改。
diff_list = []
listA = ["book","2","stage","me","you"]
listB = ["stage","me","you"]
for k in listB:
try:
while True:
listA.remove(k)
print k
except:
diff_list.append(k)
print listA
print diff_list
输出
stage
me
you
['book', '2']
['stage', 'me', 'you']