目标是创建一个函数作为输入列表,并返回列表的副本,并进行以下更改:字符串包含所有字母 转换为大写整数和浮点数的值增加 1个布尔值被否定(False变为True,True变为False)。
列表被替换为单词“List”该函数应该离开 原始输入列表不变。
我是新手,所以我不知道为什么我的代码无效。如果你可以帮忙解决并解释我做错了什么,那将非常感激!
def copy_me(list_input):
count = 0
new_list = []
for list_input in new_list:
if (list_input.isalpha()):
list_input.upper()
count += list_input
elif (list_input.isdigit()):
list_input = list_input + 1
count += list_input
elif (list_input.islist()):
list_input = "List"
count += list_input
return count
答案 0 :(得分:1)
下面是一个开始。一次一个地修复这些事情中的每一个,并验证它是否在每一步都有效。
def copy_me(list_input):
count = 0
new_list = []
for list_input in new_list: #you both shadow 'list_input' here AND try to iterate through the empty 'new_list', so nothing will happen
if (list_input.isalpha()): #you're calling function 'isalpha' on 'list_input' and you don't even know if it has the method. what if, e.g., it's an integer? this will fail
list_input.upper() #upper does not occur in place
count += list_input #you are trying to add a str to an int
elif (list_input.isdigit()): #again, calling function when you don't know if 'list_input' has it
list_input = list_input + 1 #overwriting iterating var, will be ignored on next loop
count += list_input #again, adding str to int
elif (list_input.islist()): #don't know what islist is
list_input = "List" #overwriting iterating var, will be ignored on next loop
count += list_input #more type errors involving addition
答案 1 :(得分:0)
鉴于您上面的评论解释了代码的预期目的,主要问题是您正在返回计数变量,这似乎没有任何用途。你也使用了一些错误的方法。例如,isalpha()不检查对象是否是字符串,它检查字符串中的每个字符是否都是字母。如果你传递“foo1”,什么都不会发生。这种误解会延续到islist(),它实际上并不存在。我认为你在寻找的是type()或isinstance()。
以下是修订版:
def copy_me(list_input):
new_list = []
for item in list_input:
if isinstance(item, str):
new_list.append(item.upper())
elif isinstance(item, int):
new_list.append(item + 1)
elif isinstance(item, float):
new_list.append(item + 1.0)
elif isinstance(item, list):
new_list.append("List")
else:
new_list.append(item)
return new_list
使用此代码,copy_me([1,'lower',2.0,[]]将返回[2,'LOWER',4.0,'List']。