简体   繁体   English

Python 3.x-如何在两个字符串中查找字符集的交集

[英]Python 3.x - How to find the intersection of the sets of characters in two strings

This is the code I am trying to edit but I do not know how: 这是我要编辑的代码,但我不知道如何:

var1= 'ABC'
var2= 'DBC'
match= any(x in var1 for x in var2)
if any(x in var1 for x in var2):
    print("var1 in var2")
    print("The letters that are in var1 and var2 are", match)
else:
    print("No results.")

When I run that code I get these results that are useless for me: 当我运行该代码时,得到的这些结果对我来说是无用的:

var1 in var2
The letters that are in var1 and var2 are True

What I want the program to do is to: 我希望程序执行以下操作:

var1 in var2
The letters that are in var1 and var2 are BC

If were to change var1 to ABD I want the result to be: 如果要将var1更改为ABD,我希望结果是:

var1 in var2
The letters that are in var1 and var2 are BD

PS I also want it to print the letters in alphabetical order: So I want the result to be like The letters that are in var1 and var2 are BD , and not The letters that are in var1 and var2 are DB . PS我也希望它按字母顺序打印字母:所以我希望结果像The letters that are in var1 and var2 are BD The letters that are in var1 and var2 are DB The letters that are in var1 and var2 are BD ,而The letters that are in var1 and var2 are BD The letters that are in var1 and var2 are DB

Thank you very much. 非常感谢你。 Your sincerely. 忠实于你的。

var1= 'ABC'
var2= 'DBC'
match= [x for x in var1 if x in var2]
if match:
    print("var1 in var2")
    match_str = ''.join(sorted(match))
    print("The letters that are in var1 and var2 are %s." % match_str)
else:
    print("No results.")

This prints: 打印:

var1 in var2
The letters that are in var1 and var2 are BC.

Basically I'm using a list comprehension to find which elements are the same, checking if the list is non-empty with if match , sorting using the sorted function, and then concatenating each element into a single string with ''.join (joining with empty string '' because we don't want spaces between the letters). 基本上,我使用列表推导来查找哪些元素相同,使用if match检查列表是否为非空,使用已sorted函数进行sorted ,然后使用''.join''.join使用空字符串''因为我们不需要字母之间的空格)。

Then, to avoid having commas in the output, I use % format syntax to insert the sorted characters into the output sentence. 然后,为避免在输出中出现逗号,我使用%格式语法将排序后的字符插入输出语句。

You can also use set arithmetic to do this. 您也可以使用设置算法来执行此操作。

>>> var1 = 'ABC'
>>> var2 = 'DBC'
>>> ''.join(set(var1).intersection(set(var2)))
'CB'

Changing var1 , 更改var1

>>> var1 = 'ABD'
>>> ''.join(set(var1).intersection(set(var2)))
'BD'

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

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