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.
JavaScript
x
3
1
List_A = ["apple123","banana3","345banana","cat123","apple456"]
2
List_B = ["apple123","345123","dog234","apple4","cat002345"]
3
The following is the for loop of printing the overlap data between List_A and List_B.
JavaScript
1
4
1
for i in List_A:
2
if i in List_B:
3
print(i)
4
The output is
JavaScript
1
2
1
apple123
2
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.
JavaScript
1
12
12
1
List_A1 = []
2
for i in List_A:
3
List_A1.append(i[0:3])
4
5
List_B1 = []
6
for i in List_B:
7
List_B1.append(i[0:3])
8
9
# check if any top 3 letters overlap
10
for i in List_A1:
11
if i in List_B1: print(i)
12
the output is
JavaScript
1
5
1
app
2
345
3
cat
4
app
5
However, my expected output is the original data in List_B, such as:
JavaScript
1
5
1
apple123
2
345123
3
apple4
4
cat002345
5
May I ask how could I modify the code?
Advertisement
Answer
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.
JavaScript
1
5
1
# for i in List_A1: # changes from here...
2
for i in range(len(List_A1)): # per each index i in List_A1
3
if List_A1[i] in List_B1: # element i overlapped in List_B1
4
print(List_A[i]) # print the item in List_A by same index
5