简体   繁体   English

比较 2 个变量字符 (Python)

[英]Comparing 2 variables characters (Python)

I want to compare 2 string variables and return the number of characters that are shared between the 2 strings.我想比较 2 个字符串变量并返回两个字符串之间共享的字符数。 So "work" and "what" would return "1/4" since 1 out of 4 letters (only w in this example) are the same between the 2 strings.因此, "work""what"将返回“1/4”,因为 4 个字母中有 1 个(在此示例中仅w )在 2 个字符串之间相同。

This gives you the number of letters that appear in both words in the same position:这为您提供了出现在同一位置的两个单词中的字母数:

sum(1 for a, b in zip(word1, word2) if a == b)

zip gives you an iterator for each character in both words at the same time, and you simply sum 1 for each time they match. zip为您提供两个单词中每个字符的迭代器,并且您只需为每次匹配时求和1

This gives you the generally shared letters between both words in any position:这为您提供了任何位置的两个单词之间通常共享的字母:

len(set(word1) & set(word2))

This creates two sets of letters, takes the intersection of both sets, and tells you how big that intersection is.这将创建两组字母,取两组字母的交集,并告诉您该交集有多大。

Are you asking for something like this?你要求这样的东西吗?

a = "hello"
print(list(a))

b = "hell"

counter=0
for x in list(a):
    if x in list(b):
    counter+=1

print(str(counter)+"/"+str(len(list(b))))

This is taking the string stored in variable a, looping through the characters and comparing to the string stored in variable b.这是获取存储在变量 a 中的字符串,循环遍历字符并与存储在变量 b 中的字符串进行比较。 Finally;最后; it prints the number of characters in a that were also in b over the length of the string stored in b.它在存储在 b 中的字符串的长度上打印 a 中也在 b 中的字符数。

You might what to consider using difflib as it seems to cover your usecase but also extends it to strings of different lengths.您可能会考虑使用difflib因为它似乎涵盖了您的用例,而且还将其扩展到不同长度的字符串。

Example 1示例 1

import difflib

sequence_matcher = difflib.SequenceMatcher(a='work', b='what')

sequence_matcher.ratio() # 0.25

Example 2示例 2

import difflib

sequence_matcher = difflib.SequenceMatcher(a='work', b='works')

sequence_matcher.ratio() # 0.889

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

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