如何通过使用 Python 3 修剪前 3 个字母来打印两个列表的重叠值

How do I print the overlap value from two lists by trimming the first 3 letters using Python 3

我的目标是使用 Python 3 检查 List_A 和 List_B 之间是否有重叠的前 3 个字母,并打印 List_B 的重叠数据.

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

下面是打印List_A和List_B重叠数据的for循环。

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

输出为

apple123

接下来,我尝试select将前3个字母追加到新的A和B列表中,然后比较是否有重叠。

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)

输出是

app
345
cat
app

然而,我期望的输出是List_B中的原始数据,如:

apple123    
345123
apple4
cat002345

请问如何修改代码?

如果我理解你想要实现的目标,你可以像这样简化你的代码:

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']

代码正在打印 3 个字母列表中的元素。您可能首先获取其索引并在原始列表中打印与相同索引重叠的部分。

# 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