我遇到的问题是,如果要复制一份,我们就会改变列表本身 以下是我到目前为止所做的事情:
def mutate_me(my_list):
'''(list)-> NoneType
returns my_list mutated the same way
as the function copy_me
>>>test_list = [1, 2.5, "1abc", [1, 2, 3], False]
>>>mutate_me(test_list)
>>>test_list = [2, 3.5, "1ABC", "List", True]
>>>test_list = [2, False, ["list"], "Hello", 1.0]
>>>mutate_me(test_list)
>>>test_list = [3, True, "List", "HELLO", 2.0]
'''
# go through every element in the list
# check there type and based upon there
# type apply the rule
for element in my_list:
if(type(element) == str):
for i in element:
if(i.isalpha()):
element = element.upper()
my_list.append(element)
elif(type(element) == int or type(element) == float):
element = element + 1
elif(type(element) == bool):
element = not element
elif(type(element) == list):
element = "List"
else:
element
答案 0 :(得分:2)
def mutate_me(my_list):
for idx, element in enumerate(my_list):
if(type(element) == str):
my_list[idx] = element.upper()
elif(type(element) == int or type(element) == float):
my_list[idx] = element + 1
elif(type(element) == bool):
my_list[idx] = not element
elif(type(element) == list):
my_list[idx] = "List"
答案 1 :(得分:1)
以下是解决方案的一小部分示例
for i, element in enumerate(my_list):
if(type(element) == str):
my_list[i] = element.upper()
迭代时需要枚举变异