函数实现列表中正数更改为负数
>>:
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.
invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []
You can assume that all values are integers. Do not mutate the input array/list.
遍历列表,并将每个项目与给定的数字进行比较,返回时给定的数字应该是负数
>>:想法:
与0 进行大小比较 得到正负信息,负数输出到空列表中,正数 * -1,输出到列表
1 def invert(lst): 2 lst_new = [] 3 for n in lst: 4 if n >= 0: 5 lst_new.append(n * -1) 6 else: 7 lst_new.append(n) 8 print(lst_new) 9 10 invert([1,2,3,4,5]) 11 invert([1,-2,3,-4,5]) 12 invert([])
[-1, -2, -3, -4, -5] [-1, -2, -3, -4, -5] []