比较列表中的每个元素

Compare each of element in list

是否可以匹配两个元组,逐一比较每一个元素,判断哪里发生了变化。

注: runA 和 runB 输出在循环中,所以这意味着它不是硬编码的。 runA 和 runB 的范围可以是 tool01 到 tool100 或仅 tool01 等,具体取决于我的查询的循环结果。只是工具在 for 循环中,所以工具号可以或多或少。

我的输出#1 的示例结果:

runA = [(u'tool01', '21'), (u'tool02', '22'), (u'tool03', '23')]

runB = [(u'tool01', '21'), (u'tool02', '22'), (u'tool03', '22')]

预期结果 #1:

print 'there is a changes on tool03'  

我的输出#2 的示例结果:

runA = [(u'tool01', '21'), (u'tool02', '22'), (u'tool03', '23')]

runB = [(u'tool01', '20'), (u'tool02', '21'), (u'tool03', '23')]

预期结果 #2:

print 'there is a changes on tool01' 
print 'there is a changes on tool02' 

我的输出#3 的示例结果:

runA = [(u'tool01', '21'), (u'tool02', '22'), (u'tool03', '23')]

runB = [(u'tool01', '21'), (u'tool02', '22'), (u'tool03', '23')]

预期结果 #3:

print 'there is no change'

任何建议或基础代码,在此先感谢。

注: runA 和 runB 输出在循环中,因此这意味着它不是硬编码的。 runA 和 runB 的范围可以是 tool01 到 tool100 或仅 tool01 等,具体取决于我的查询的循环结果。只是工具在 for 循环中,所以工具号可以或多或少。

for i in runA - 1:
  If runA[i][1] != runB[i][1]:
    print 'there is a changes in ' + runA[i][0]

这是假设两件事:

  1. the lists are of equal lengths
  2. the tuple names have the same indices

正如您的一位评论者所建议的那样,使用字典会更容易,因为您可以遍历键并使用 d[key]

访问成员
#/bin/python
confirm_change=False

runA = [(u'tool01', '21'), (u'tool02', '22'), (u'tool03', '23')]

runB = [(u'tool01', '20'), (u'tool02', '21'), (u'tool03', '23')]

for i in runA:
    for j in runB:
        if i[0]==j[0] and not i[1]==j[1]:
            confirm_change=True
            print("there is a change in",i[0])
if confirm_change==False:
    print("There is no change")

下一个函数应该可以满足您的需求:

def matchTuples(runA, runB):
    equal = True
    for i in range(0, len(runA) ):
        if runA[i] != runB[i]:
            equal = False
            print 'there is a change on ' + runA[i][0]
    if equal:
        'there is no change'

它遍历列表以检查它们是否相等。如果有变化,那么它会打印被更改的元组的名称。

最后,如果没有检测到任何变化(也就是说,如果变量 "equal" 仍然为 True),它会打印 'there is no change'.

runA = [(u'tool01', '21'), (u'tool02', '22'), (u'tool03', '23')]
runB = [(u'tool01', '21'), (u'tool02', '22'), (u'tool03', '22')]
for i in range(len(runA)):
    if runA[i] == runB[i]:
        print True
    else:
        print False