Afsheen Taheri
Afsheen Taheri

Reputation: 139

Python trouble with matching tuples

For reference this is my code:

list1 = [('10.180.13.101', '10.50.60.30', 'STCMGMTUNIX01')]
list2 = [('0.0.0.0', 'STCMGMTUNIX01')]

for i in list1:
    for j in list2:
        for k in j:
            print (k)
            if k.upper() in i:
                matching_app.add(j)


for i in matching_app:
    print (i)

When I run it, it does not match. This list can contain two or three variables and I need it to add it to the matching_app set if ANY value from list2 = ANY value from list1. It does not work unless the tuples are of equal length.

Any direction to how to resolve this logic error will be appreciated.

Upvotes: 1

Views: 154

Answers (2)

JacobIRR
JacobIRR

Reputation: 8966

You can solve this in a few different ways. Here are two approaches:

Looping:

list1 = [('10.180.13.101', '10.50.60.30', 'STCMGMTUNIX01')]
list2 = [('0.0.0.0', 'STCMGMTUNIX01')]
matches = []
for i in list1[0]:
    if i in list2[0]:
        matches.append(i)
print(matches)
#['STCMGMTUNIX01']

List Comp with a set

merged = list(list1[0] + list2[0])
matches2 = set([i for i in merged if merged.count(i) > 1])
print(matches2)
#{'STCMGMTUNIX01'}

Upvotes: 1

figbeam
figbeam

Reputation: 7176

I'm not clear of what you want to do. You have two lists, each containing exactly one tuple. There also seems to be one missing comma in the first tuple.

For finding an item from a list in another list you can:

list1 = ['10.180.13.101', '10.50.60.30', 'STCMGMTUNIX01']
list2 = ['0.0.0.0', 'STCMGMTUNIX01']

for item in list2:
    if item.upper() in list1: # Check if item is in list
        print(item, 'found in', list1)

Works the same way with tuples.

Upvotes: 0

Related Questions