简体   繁体   English

只需要在 for 循环外打印一次

[英]Need to print only once outside the for loop

I am trying to print "True" if the input string has two consecutive identical letters.如果输入字符串有两个连续的相同字母,我正在尝试打印“True”。 Foe ex: a="Matthew".For this input it should print True since the word 'Matthew' has two consecutive identical letters ("t").例如:a="Matthew"。对于这个输入,它应该打印 True,因为单词 'Matthew' 有两个连续的相同字母(“t”)。 Similarly print False for the word "John" since it has no consecutive letters.类似地,为单词“John”打印 False,因为它没有连续的字母。

Code:代码:

 a="Matthew"

 for i in range(len(a)-1):
    if a[i]==a[i+1]:
       print("True")
    else:
       print("False")

Output: False, False, True, False, False, False Output:假,假,真,假,假,假

Just needed to print only once "True" if there are consequtive letters and needed to print only once "False" if there are no consequtive letters.如果有后续字母,只需打印一次“True”,如果没有后续字母,则只需打印一次“False”。

use an other variable使用其他变量

a="Matthew"
double = False

for i in range(len(a)-1):
   if a[i]==a[i+1]:
      double = True
      break
print(double)

Just for posterity's sake, I thought you might find it interesting to know that regex offers a much more concise solution:只是为了后代的缘故,我想您可能会发现知道 regex 提供了一个更简洁的解决方案很有趣:

a = "Matthew"
if re.search(r'(.)\1', a) :
    print("MATCH")
else:
    print("NO MATCH")

Python has for-else loop. Python 有for-else循环。 So, it can be done this way too:所以,它也可以这样做:

a = "Matthew"

    for i in range(len(a)-1):
        if a[i]==a[i+1]:
          print("True")
          break
    else:
         print("False")

Output: True Output: True

The else part executes only when the for-loop has iterated through the range; else部分仅在for-loop遍历范围时执行; any break in between will lead to skipping the execution of else part.中间的任何break都将导致跳过else部分的执行。

So, if the input were a="Mathew" , it will print false因此,如果输入是a="Mathew" ,它将打印false

>>> print(any(i == j for i, j in zip(a[:-1], a[1:])))
True
# i j
# - -
# M a  No match.
# a t  No match.
# t t  Match. Done.
# t h
# h e
# e w

Or a slightly more performant but more verbose version (of course the re.search method is faster still but requires an understanding of regular expressions):或者性能稍高但更冗长的版本(当然re.search方法更快,但需要了解正则表达式):

c = a[0]
for c2 in a[1:]:
    if c == c2:
        print('True')
        break
    c = c2

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

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