简体   繁体   English

如何将两个字符串中的连续字符与循环进行比较?

[英]How do I compare sequential characters in two strings with loops?

I have two strings 'hello' and 'leetcode' inside an array words.我在数组单词中有两个字符串“hello”和“leetcode”。

I am struggling to compare each of the characters in the string, one by one - so for example, I want to compare我正在努力逐一比较字符串中的每个字符 - 例如,我想比较

  • 'h' with 'l' 'h' 与 'l'
  • 'e' with 'e' 'e' 与 'e'
  • 'l' with 'e' 'l' 与 'e'
  • and so on.等等。

I have written the following for loops below, but they don't seem to do the job, as it prints the wrong result.我在下面编写了以下 for 循环,但它们似乎没有完成这项工作,因为它打印了错误的结果。

words = ["hello","leetcode"]

for j in range(len(words)):
    for k in range(len(words[j])):
        if words[j][k] < words[j + 1][k]:

Any idea how to amend the above, or suggest another way to do this?知道如何修改上述内容,或建议另一种方法吗?

Fix使固定

You need one for loop that generates indices for both words您需要一个为两个单词生成索引的for循环

words = ["hello", "leetcode"]
for j in range(min(len(words[0]), len(words[1]))):
    if words[0][j] < words[1][j]:
        print("LO")
    elif words[0][j] > words[1][j]:
        print("UP")
    elif words[0][j] == words[1][j]:
        print("EQ")

Improve提升

You can iterate on pair using zip , that directly yields chars of each words您可以使用zip对对进行迭代,这直接产生每个单词的字符

words = ["hello", "leetcode"]
for c1, c2 in zip(*words):
    if c1 < c2:
        print("LO")
    elif c1 > c2:
        print("UP")
    elif c1 == c2:
        print("EQ")

I would let Python split out the characters for me:我会让 Python 为我拆分字符:

for a, b in zip(*words):
    if a==b:
        print(f"{a}=={b}")
    else:
        print(f"{a}!={b}")

h!=l
e==e
l!=e
l!=t
o!=c

If there are more than two words, the technique is the same:如果有两个以上的词,技术是一样的:

>>> words = ["hello","leetcode","hellooo"]
>>> list(zip(words))
>>> [('h', 'l', 'h'), ('e', 'e', 'e'), ('l', 'e', 'l'), ('l', 't', 'l'), ('o', 'c', 'o')]

As you can see, this will work for any number of words.如您所见,这适用于任意数量的单词。 But it is unclear what you would then mean by match .但目前还不清楚match是什么意思。 If you are looking for a match at the same position in all the words, you could do it this way:如果您正在寻找所有单词中相同 position 的匹配项,您可以这样做:

words = ["hello","leetcode","hellooo"]
for index, mytuple in enumerate(zip(*words)):
    if len(set(mytuple)) == 1:
        print(f"Match on {mytuple[0]} at position {index}")

    
Match on e at position 1

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

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