【发布时间】:2017-03-12 14:53:14
【问题描述】:
def copy_me(input_list):
''' (list) -> list
This function will copy the list and will do the following to it:
change every string into an upper case, increase the value of every
integer and float by 1, negate every boolean and replace lists with the
word 'List'. After the modifications are made, the copied list will be
returned. (The original inputted list won't be mutated)
REQ: The list must only contain the following data types: str, int,
float, bool, list.
>>> copy_me(['hi', 1, 1.5, True, ['sup', 123])
['HI', 2, 2.5, False, 'List']
'''
# Copy the list
copied_list = input_list.copy()
# Go through each element of list
for index, element in enumerate(copied_list):
print(type(element))
if (type(element) == str):
copied_list[index] = element.upper()
elif (type(element) == int or float):
copied_list[index] = element + 1
elif (type(element) == bool):
if (element == True):
copied_list[index] = False
elif (element == False):
copied_list[index] = True
print(copied_list)
做类似的事情:
>>> copy_me([True])
[2]
这对我来说毫无意义。谁能解释为什么以及如何让它返回 False 作为值?
【问题讨论】:
-
type(element) == int or floatdoesn't mean what you think it means。这被解析为(type(element) == int) or float)。由于float是真实的,因此该分支将始终执行,除非它上面的分支已经执行... -
在 if 语句中不应该 float 为 false 吗?不过好吧,我想我明白了,谢谢!
-
不。在 python 中,大多数 事物都是真实的(包括所有内置类型)。
-
此外,基于“REQ”部分,您似乎错过了使用递归的机会(例如,如果您得到一个包含另一个列表的列表!):-)
-
还没有学会递归 D:,但它应该正确处理它,它将完全摆脱列表并将其替换为“列表”;D