簡體   English   中英

比較列表中的每個元素

[英]Compare each of element in list

是否可以匹配兩個元組,將每個元素一一比較,然后確定更改發生在哪里。

注意: runA和runB輸出在循環中,因此這意味着它不是硬編碼的。 runA和runB的范圍可以是tool01到tool100或僅tool01等,這取決於將結果循環到我的查詢中。 只是該工具位於for循環中,所以該工具no或多或少。

我的輸出#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循環中,所以該工具no或多或少。

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

這是假設兩件事:

  1. 列表的長度相等
  2. 元組名稱具有相同的索引

正如您的一位評論者所建議的那樣,使用字典將更加容易,因為您可以遍歷鍵並使用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'

遍歷列表以檢查它們是否相等。 如果有更改,那么它將打印已更改的元組的名稱。

最后,如果未檢測到任何變化(即,如果變量“等於”仍為True),則打印“沒有變化”。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM