简体   繁体   English

理解列表与for循环

[英]comprehension list vs for loop

I have written a simple program that will take the first letter of a string and capitalize it. 我编写了一个简单的程序,该程序将字符串的首字母大写。

def initials(text):
    words = text.split()
    a=[word[0].upper() for word in words]
    b = '. '.join(a) + '.'
    return b
text = "have a good day sir"

print(initials(text))

This will give me the result i want by using a list comprehension. 通过使用列表理解,这将给我想要的结果。 however i cannot make it work by using a typical FOR LOOP as below and it will give me only the last iteration: 但是我不能通过使用如下所示的典型FOR LOOP来使其工作,它只会给我最后一次迭代:

def initials(text):
    words = text.split()
    for word in words:
        a=word[0].upper()
        b = '.'.join(a) + '.'
    return b
text = "have a good day sir"

print(initials(text))

any idea why the second example doesn't work as the first one? 知道为什么第二个示例不能像第一个示例那样工作吗?

b is being reset every time around the loop in the second case. 在第二种情况下,每次循环时b都会复位。 So you only get the last initial followed by . 因此,您只会得到最后一个首字母,然后是. . The equivalent to your comprehension in a for loop, would be: 相当于您对for循环的理解是:

def initials(text):
    words = text.split()
    a = []
    for word in words:
        a.append(word[0].upper())
    b = '.'.join(a) + '.'
    return b

You're overwriting b on each loop iteration. 您在每次循环迭代中都覆盖b。 Try: 尝试:

def initials(text):
    words = text.split()
    for word in words:
        a = word[0].upper()
        b += '.'.join(a) + '.'
    return b
text = "have a good day sir"

The problem is that str.join() takes a iterable of strings, but in your second function you are passing a single chararacter. 问题在于str.join()需要一个可迭代的字符串,但是在第二个函数中,您传递了一个字符。 The fact that you are calling it inside the loop does not convert it into a list of characters. 您在循环内调用它的事实不会将其转换为字符列表。

The easiest way for you is to get rid of the str.join() and use a simple string to accumulate the result: 最简单的方法是摆脱str.join()并使用简单的字符串来累加结果:

def initials(text):
    words = text.split()
    b = ''
    for word in words:
        a=word[0].upper()
        b += a + '.'
    return b

If you insist in using str.join() you will need a list to accumulate your initials: 如果您坚持使用str.join() ,则将需要一个列表来积累您的姓名首字母:

def initials(text):
    words = text.split()
    b = []
    for word in words:
        a=word[0].upper()
        b.append(a)
    return '.'.join(b) + '.'

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

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