在函数中将正数更改为负数

时间:2016-04-28 19:55:09

标签: python function python-3.x return

我一直在网上浏览我的问题,但似乎无法找到任何帮助。

问题是你应该有一个随机的数字列表然后返回列表,但是,返回时给定的数字应该是负数而不是正数。这是我到目前为止所提出的:

#include "Shape.h"

class Circle  : public Shape {
    public:
    Circle(const string& newColor, int newRadius);
    virtual ~Circle();
    double getArea();
    void print() const;

    private:
    int radius;
};

Circle::Circle(const string& newColor, int newRadius) {
    radius = newRadius;
    Shape(newColor);
}

double Circle::getArea() {
    return (3.14*radius*radius);
}

void Circle::print() const{
    print(Shape);
    cout << "circle, radius " << radius;
}

因此,如果给定的数字(n)在列表中,它应该返回相同的列表,但是将n作为负数。

希望这是有道理的,如果有人能找到时间帮助我,我将非常感激!

4 个答案:

答案 0 :(得分:2)

您需要遍历列表,并将每个项目与您给定的数字进行比较。

def change_sign(list, n):
    new_list = []
    for value in list:
        if value == n:
            value = -value
        new_list.append(value)

    return new_list

您可以使用列表理解来清除它:

def change_sign(list, n):
    return [value if value != n else -value for value in list]

如果您不理解这一点,请不要担心,这将在以后的练习中介绍。

答案 1 :(得分:0)

如果我们要返回一个新列表,这将为您完成(也不要将单词列表用作变量,它是一个保留字!):

def change_sign(numbers_list,invert_this_number):
    inverted_numbers_list = []
    for number in numbers_list:
        if number == invert_this_number:
            inverted_numbers_list.append(number * -1)
        else:
            inverted_numbers_list.append(number)
    return inverted_numbers_list


>>> change_sign([-1,1,3],-1)
[1, 1, 3]

你可能会做一些花哨的操作符,比如对整数本身进行按位操作,但是这个简单的代码片段就足够了。

答案 2 :(得分:0)

您可以使用list comprehensionsmap

返回新列表
n = 5
old_list = [0, 4, 3, -2, 5, -5, 6]
new_list = [-i if i == n else i for i in old_list]
# OR
new_list = map(lambda i: -i if i == n else i, old_list)

或者如果你绝对需要它的功能形式:

def func(old_list, n):
    return [-i if i == n else i for i in old_list]

请注意,这些都希望n为正数。如果你想要它处理正数和负数(负数将返回一个基本不变的列表)

def func(old_list, n):
    if n <= 0:
        return old_list[:]
    return [-i if i == n else i for i in old_list]

答案 3 :(得分:0)

您可以执行以下操作:

def change_sign(list1,n):
    if n in list1:
        return [-i if i==n else i for i in list1]
    elif n not in list1:
        print("The number is not in the list")

这会回答你的问题吗?

列表理解非常强大!玩得开心!