Spe*_*e43 2 python indexing methods function list
我创建了一个Python函数,它接受一个参数,fullname,获取fullname的首字母并将它们打印出来.但是我的代码存在问题 - 它只适用于两个名称.如果全名有一个中间名,即Daniel Day Lewis,则会中断.
这是我尝试过的:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
return(first.upper() + second.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
Run Code Online (Sandbox Code Playgroud)
显然,这种尝试只包括两个变量,一个用于第一个名称,另一个用于第二个名称.如果我添加第三个变量,如下所示:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
third = name_list[2][0]
return(first.upper() + second.upper() + third.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
Run Code Online (Sandbox Code Playgroud)
我明白了:
IndexError: list index out of range on line 10
Run Code Online (Sandbox Code Playgroud)
(这是线)
third = name_list[2][0]
Run Code Online (Sandbox Code Playgroud)
当然,如果我将fullname更改为"Ozzie Smith Jr",此功能确实有效.但是无论fullname中是否有1,2,3或4个名称,我的函数都必须工作.我需要说:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
#if fullname has a second name:
second = name_list[1][0]
#if fullname has a third name:
third = name_list[2][0]
#if fullname has one name:
return(first.upper())
#if fullname has two names:
return(first.upper() + second.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper + fourth.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
Run Code Online (Sandbox Code Playgroud)
如何在Python中说"如果fullname具有第二个名称或第三个名称或第四个名称,则返回大写首字母"?还是我走在正确的轨道上?谢谢.
您可以使用列表理解:
s = ''.join([x[0].upper() for x in fullname.split(' ')])
Run Code Online (Sandbox Code Playgroud)
编辑:应该可以解释更多列表推导允许您在迭代时构建列表.首先,我们通过将fullname与空格分开来构建列表fullname.split(' ').当我们得到这些值时,我们取第一个字母x[0]并大写它.upper().最后,我们将列表加入到没有空格的列表中''.join(...).
这是一个非常好的一个班轮,非常快,并会在你继续使用python时以各种形式弹出.
怎么样:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
initials = ""
for name in name_list: # go through each name
initials += name[0].upper() # append the initial
return initials
Run Code Online (Sandbox Code Playgroud)