我想简单地从两个列表中减去元素

时间:2015-02-14 12:00:24

标签: python list subtraction

我有两个公开名单。第一个体重(fWeight)和第二个体重(sWeight)。我想从fWeight中减去sWeight。我收到了这个错误:

unsupported operand type(s) for -: 'list' and 'list'.

有一个简单的解决方案吗?

names_array = list()
firstWeight_Array=list()
students = 2
for i in range(students):
    name = str(raw_input("Please enter a  name:"))
    names_array.append(str(name))
    fWeight = int(raw_input("Please enter the first weight:"))
    firstWeight_Array.append(int(fWeight))

SecondWeight_Array=list()
for i in range(students):
        sWeight = int(raw_input("Please enter the Second weight:"))
        SecondWeight_Array.append(int(sWeight))

print(firstWeight_Array,SecondWeight_Array)
print firstWeight_Array - SecondWeight_Array

3 个答案:

答案 0 :(得分:1)

没有为list定义减法运算符,因为它在一般方面没有意义。但是,您只需使用[]运算符获取单个项目,然后计算新list中的差异:

newArray = list();
for i in xrange(students):
    newArray.append(firstWeight_Array[i] - secondWeight_Array[i]);
print newArray;

答案 1 :(得分:0)

如果你需要将一个列表中的每个项目减去相同大小的第二个列表的相应项目,最简单的方法(可能是最惯用的方法)是使用list comprehension和{{3功能:

diff = [first - second 
        for first, second in zip(firstWeight_Array, secondWeight_Array)]

这是一个简单的例子:

>>> firstWeight_Array = [10,20,30]
>>> secondWeight_Array = [12,18,34]

>>> diff = [first - second 
...         for first, second in zip(firstWeight_Array, secondWeight_Array)]

>>> diff
[-2, 2, -4]

请注意,出于节省空间的原因,在Python 2中,您可能更喜欢使用zip而不是普通zip

答案 2 :(得分:0)

我愿意:

diffs = [firstWeight_Array[i] - secondWeight_Array[i] for i in xrange(len(students))]

如果您使用的是Python 3,请使用range代替xrange