简体   繁体   English

如何使两个不同的字符串列表相同?

[英]How to make two different list of strings same?

I have two random lists of strings.我有两个随机的字符串列表。 The length of two lists won't be necessarily equal all the time.两个列表的长度不一定总是相等。 There is no repetition of the elements within a list.列表中的元素没有重复。

list1=['A', 'A-B', 'B', 'C']
list2=['A', 'A-B', 'B', 'D']

I want to compare the two lists, and the final output should be two lists with all common elements.我想比较两个列表,最终的 output 应该是所有共同元素的两个列表。

Expected output:预计 output:

list1_final=['A', 'A-B', 'B', 'C','D']
list2_final=['A', 'A-B', 'B','C', 'D']

How can I achieve this with a minimum number of lines of code?我怎样才能用最少的代码行数来实现这一点?

Use the set python module.使用设置 python 模块。 Just using set1.intersection(set2) you can have the common elements between set1 and set2.只需使用set1.intersection(set2)您就可以拥有 set1 和 set2 之间的公共元素。 Or using set1.union(set2) for the union set.或者使用set1.union(set2)作为并集。

Youve requested 2 lists with all common elements:您已请求 2 个包含所有常见元素的列表:

list1=['A', 'A-B', 'B', 'C']
list2=['A', 'A-B', 'B', 'D']

list1_final=[]
list2_final=[]

for item in list1:
    if item in list2:
        list1_final.append(item)
        list2_final.append(item)

returns回报

list 1 = ['A', 'A-B', 'B'] list 2 = ['A', 'A-B', 'B']列表 1 = ['A', 'A-B', 'B'] 列表 2 = ['A', 'A-B', 'B']

Now your output doesnt match the question asked, do you want all items in both lists?现在您的 output 与所问的问题不匹配,您是否需要两个列表中的所有项目? not just the common ones?不仅仅是普通的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM