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

2024-06-24 12:09:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是使用Python 3检查列表A和列表B之间是否有任何前3个字母重叠,并从列表B打印重叠数据

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

下面是打印列表A和列表B之间重叠数据的for循环

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

输出是

apple123

接下来,我尝试选择前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

但是,我的预期输出是列表_B中的原始数据,例如:

apple123    
345123
apple4
cat002345

请问如何修改代码


Tags: 数据inapp列表forifa1字母
2条回答

代码正在打印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

如果我了解您试图实现的目标,您可以将代码简化为:

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

相关问题 更多 >