Home > Enterprise >  Checking elements from two arrays
Checking elements from two arrays

Time:02-02

I have two diferent arrays and I need to know if the name from the first array "date" is in the second array "name"

date = ['Olivia Smith', 'Jacob Williams', 'Jessica Taylor', 'Harry Miller']
name = ['Olivia', 'Jessica', 'Jacob', 'James']

for i in range(len(data)):
    x = 0
    print(name.index(data[x]))
    x = x   1
    i = i   1

I want the program to confirm that the name from the 'data' array is in the 'name' array

CodePudding user response:

Use list comprehension and string.split() to grab just the first names. Then use another list comprehension to grab the intersect.

date = ['Olivia Smith', 'Jacob Williams', 'Jessica Taylor', 'Harry Miller']
name = ['Olivia', 'Jessica', 'Jacob', 'James']

date_fn = [full_name.split()[0] for full_name in date]

names_in_both = [first_name for first_name in date_fn if first_name in name]

CodePudding user response:

Use split and grab the first part. then iterate and compare.

new_date = [name.split(' ')[0] for name in date]

for name in set(name):
    if name in new_date:
        print(f"{name} is found!.")

CodePudding user response:

You can use a comprehension:

out = [sum(x in y for y in date) for x in name]
print(*zip(name, out), sep='\n')

# Ouput:
('Olivia', 1)
('Jessica', 1)
('Jacob', 1)
('James', 0)

CodePudding user response:

If you want to check that any one exists (returns bool):

any(i.split()[0] in name for i in date)

If you want to check that all exist (returns bool):

any(i.split()[0] in name for i in date)

If you want to retrieve the ones that exist:

def intersection(a, b):
    res = []
    for i in a:
        if i.split()[0] in b:
            res.append(i.split()[0])
    return res
print(intersection(date, name))
# Output: ['Olivia', 'Jacob', 'Jessica']

You can simplify the above function to:

def intersection(a, b):
    res = [i.split()[0] for i in a if i.split()[0] in b]
    return res

Docs:
any()
all()
List Comprehension

  • Related