简体   繁体   English

如何使用 python 按 position 计算字符串中相同字符的数量?

[英]How do I count the number of identical characters in a string by position using python?

For example:例如:

String 1: AGGCCT
          || | |
String 2: AGCCAT

These two strings are identical at 4 positions, so the function I want would return 4.这两个字符串在 4 个位置相同,因此我想要的 function 将返回 4。

Is there a clever (ie, fast) method for doing this, other than the obvious method of iterating through both strings at the same time?除了同时遍历两个字符串的明显方法之外,是否有一种聪明(即快速)的方法来做到这一点?

Thanks!谢谢! Uri乌里

I don't think any "clever" trick beats the obvious approach, if it's well executed:如果执行得当,我认为没有任何“聪明”的技巧能胜过显而易见的方法:

sum(c1 == c2 for c1, c2 in itertools.izip(s1, s2))

Or, if the use of booleans for arithmetic irks you,或者,如果在算术中使用布尔值让您感到厌烦,

sum(1 for c1, c2 in itertools.izip(s1, s2) if c1 == c2)

Though I prefer delnan's generator expression, this works as well:虽然我更喜欢 delnan 的生成器表达式,但这也适用:

>>> from itertools import imap
>>> from operator import eq
>>> sum(imap(eq, 'abcde', 'aacce'))
3

If you're looking for better performance, I suspect it will be hard to beat numpy for this:如果您正在寻找更好的性能,我怀疑这将很难击败 numpy:

import numpy as np
a1 = np.frombuffer(s1, dtype=np.byte)
a2 = np.frombuffer(s2, dtype=np.byte)
print (a1==a2).sum()

On my system, this runs about 10x faster than using itertools.在我的系统上,这比使用 itertools 快 10 倍。

暂无
暂无

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

相关问题 如何编写一个接受字符串并返回字符串中特定字符总数的函数,而不使用 .count? - How do I write a function that accepts a string and will return a total number of certain characters in the string, without using .count? 如何使用 Python 计算 csv 中唯一值的数量 - How do I count the number of unique values in a csv using Python 如何通过保持顺序来获取输入字符串并计算其中的字符数? - How do I take an input string and count the number of characters in it by maintaining the order? 如何在不使用 len() 的情况下使用累积模式计算代码中的字符数? - How do I count the number of characters in a code using accumulation pattern without using len()? 如何从 python 中的字符串中的特定 position 读取一组字符 - How do I read a set of characters from a specific position in a string in python 如何计算字符串中的字符数并显示字符和数量 - How can I count the number of characters in a string and displaying the character and amount 在Python中,我如何搜索和计数/打印列表中每个项目/字符串中的一组特定字符 - In Python how do I search for and count/print a specific set of characters in each item/string in a list 如何计算字符串中的字符? (蟒蛇) - How to count characters in a string? (python) 如何计算python中字符串中的字符数? - how to count characters in a string in python? 如何在Python中替换字符串中的字符? - How do I replace characters in a string in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM