Python – Like Index 常用字符
有时我们会遇到这类问题,我们需要将一个列表的每个元素与另一个元素相交。此类问题通常发生在我们拥有组合信息的开发中,例如不同列表中的姓名和姓氏。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + zip() + intersection()
列表推导式执行与相似索引元素相交的任务。 zip函数的任务是将结果字符串连接成单个列表和返回列表。
# Python3 code to demonstrate
# Like Index Common characters
# using list comprehension + zip() + intersection()
# initializing lists
test_list1 = ["Geeksfor", "is", "be"]
test_list2 = ['Geeks', 'sb', 'ste']
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using list comprehension + zip()
# Like Index Common characters + intersection()
res = ["".join(list(set(i).intersection(set(j)))) for i, j in zip(test_list1, test_list2)]
# printing result
print ("The list after element intersection is : " + str(res))
输出 :
The original list 1 is : ['Geeksfor', 'is', 'be']
The original list 2 is : ['Geeks', 'sb', 'ste']
The list after element intersection is : ['sGek', 's', 'e']
方法 #2:使用map() + lambda + zip() + intersection()
在该方法中,每个索引元素相互映射的任务由 map函数执行,交集的功能由 lambda 和 intersection()函数执行。此方法仅适用于Python 2。
# Python code to demonstrate
# Like Index Common characters
# using map() + lambda + zip() + intersection()
# initializing lists
test_list1 = ["Geeksfor", "is", "be"]
test_list2 = ['Geeks', 'sb', 'ste']
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using map() + lambda + zip() + intersection()
# Like Index Common characters
res = list(map(lambda(i, j): "".join(list(set(i).intersection(set(j)))), zip(test_list1, test_list2)))
# printing result
print ("The list after element intersection is : " + str(res))
输出 :
The original list 1 is : ['Geeksfor', 'is', 'be']
The original list 2 is : ['Geeks', 'sb', 'ste']
The list after element intersection is : ['sGek', 's', 'e']