python - 如何更改python列表中的索引值

标签 python list

我正在尝试检查 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' 

最佳答案

在我看来,如果您有两个字符串 stringAstringB(大概是来自 \n 上拆分的较大文本的行)这样stringB 始终是 stringA 的子字符串,并且您想在 stringA 中找到extra stuff,那么它最简单的做法是

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'

关于python - 如何更改python列表中的索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30219745/

相关文章:

python - pandas groupby 根据条件替换

c# - 我如何获得 C# 中两个列表的差异?

java - 大小为 n 的列表的所有可能的 k 组合

c# - 从列表中返回元组计数

python - 无法提供图表作为 youtube 搜索 API 的参数

python - 根据大于一行的值分配 0 和 1

python - 无法使用 pip 安装 lxml

python - 如何有效地比较 Python 中的大型列表?

python - 如何在Python中将数据框的每一行合并到一个列表中

python - 在pygame中创建多个实例