2

My goal is using Python 3 to check if there are any top 3 letters that overlap between List_A and List_B, and print the overlap data from List_B.

List_A = ["apple123","banana3","345banana","cat123","apple456"]
List_B = ["apple123","345123","dog234","apple4","cat002345"]

The following is the for loop of printing the overlap data between List_A and List_B.

for i in List_A:
    if i in List_B: 
        print(i)

The output is

apple123

Next, I try to select the first 3 letters and append them in the new List of A and B, then compare if there is any overlap.

List_A1 = []
for i in List_A:
    List_A1.append(i[0:3])

List_B1 = []
for i in List_B:
    List_B1.append(i[0:3])

# check if any top 3 letters overlap
for i in List_A1:
    if i in List_B1: print(i)

the output is

app
345
cat
app

However, my expected output is the original data in List_B, such as:

apple123    
345123
apple4
cat002345

May I ask how could I modify the code?

cjeng2
  • 23
  • 3

2 Answers2

2

If I understand what you're trying to achieve, you could simplify your code like this:

List_A = ["apple123", "banana3", "345banana", "cat123", "apple456"]
List_B = ["apple123", "345123", "dog234", "apple4", "cat002345"]

set_a = set(List_A)
set_b = set(List_B)
# Get a list of all items in List_A that also are in List_B
intercepts = list(set_a.intersection(set_b)) # Returns ['apple123']

# Get 1 line for each intercepted item
# Prints a list of the matching items in List_B vs the previous intercept,
# taking only the first 3 letters

for intercept in intercepts:
    print([i for i in List_B if i[0:3] in intercept])

# This prints ['apple123', 'apple4']
Rodrigo A
  • 657
  • 7
  • 23
1

The code was printing the elements in 3-letters list. You might first get its index and print the overlapped with same index in original list.

# for i in List_A1:               # changes from here...
for i in range(len(List_A1)):   # per each index i in List_A1
    if List_A1[i] in List_B1:   # element i overlapped in List_B1
        print(List_A[i])        # print the item in List_A by same index
Simon
  • 411
  • 6
  • 11