简体   繁体   English

检查通用字母是否在Python中两个字符串中的相同位置?

[英]Check if common letters are at the same position in two strings in Python?

I am trying to write a program that checks two strings and prints the number of common characters that are at the same position in both of the strings so if it checked, say: 我正在尝试编写一个程序,该程序检查两个字符串并打印两个字符串中相同位置的公共字符数,因此如果检查了,请说:

  1. the words 'hello' and 'heron' it would output 2 because there are two common letters at the same positions, 单词'hello''heron'将输出2因为在相同位置有两个常见字母,

  2. but if it checked 'hello' and 'fires' it would output 0 because although it has a common letter, it is not at the same position in each string. 但如果选中'hello''fires' ,则会输出0因为尽管它有一个公共字母,但在每个字符串中的位置都不相同。

How would I achieve this? 我将如何实现?

You can use zip() to iterate through both of them simultaneously: 您可以使用zip()同时遍历两个对象:

sum(1 if c1 == c2 else 0 for c1, c2 in zip(string1, string2))

or even (using implicit integer values for True and False ): 甚至(对于TrueFalse使用隐式整数值):

sum(c1 == c2 for c1, c2 in zip(string1, string2))

Let's break this down: 让我们分解一下:

zip(string1, string)

This creates a series of tuples with paired items from each of the inputs, for instance with hello and heron it looks like this: [('h', 'h'), ('e', 'e'), ('l', 'r'), ('l', 'o'), ('o', 'n')] . 这会创建一系列元组,其中每个输入项都有成对的项,例如helloheron它看起来像这样: [('h', 'h'), ('e', 'e'), ('l', 'r'), ('l', 'o'), ('o', 'n')]

for c1, c2 in

We're using a generator expression to iterate over these tuples, assigning each of the two elements to a variable. 我们使用生成器表达式遍历这些元组,将两个元素的每一个分配给一个变量。

1 if c1 == c2 else 0

We're going to emit a sequence of 1s and 0s, where the number of 1s is equal to the number of cases where the equivalent position characters were equal. 我们将发出一个1和0的序列,其中1的数目等于等效位置字符相等的情况的数目。

sum()

Finally, we sum the emitted sequence of 1s and 0s - effectively counting the total number of equal characters. 最后,我们对发出的1s和0s序列求和-有效地计算了相等字符的总数。

You can even shorten this a bit, because in Python you can treat boolean values True and False as 1 and 0 respectively, which leads to the second form above. 您甚至可以缩短一点,因为在Python中您可以将布尔值TrueFalse分别视为10 ,这导致上面的第二种形式。

You might wonder: what happens if string1 and string2 are different lengths? 您可能会想:如果string1string2的长度不同会怎样? This expression will actually still work, because zip() will stop as soon as it reaches the end of either. 该表达式实际上仍将起作用,因为zip()一旦到达任一表达式的末尾,它将立即停止。 Since by definition the extra characters in the longer string will not be equal to the lack of characters in the shorter, this doesn't affect the count. 由于按照定义,较长字符串中的多余字符将不等于较短字符串中缺少的字符,因此这不会影响计数。

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

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