I want to simply subtract elements from two lists

♀尐吖头ヾ 提交于 2019-12-02 14:36:00

问题


I have two open lists. First Weight (fWeight) and Second Weight (sWeight). I want to subtract the fWeight from sWeight. I am getting this error:

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

Is there a a simple solution for this?

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

回答1:


The substraction operator is not defined for list, as it makes no sense in a general way. However, you can simply get the single items using the [] operator, and calculate the difference in a new list:

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



回答2:


If you need to subtract every item from one list to the corresponding item of a second list of same size, the easiest way (and probably the most idiomatic way) is to use a list comprehension and the zip function:

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

Here is a simple example:

>>> 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]

Please note that for space efficiency reason, in Python 2, you might prefer using itertools.izip instead of a plain zip.




回答3:


I would do:

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

In case that you work with Python 3, use range instead of xrange



来源:https://stackoverflow.com/questions/28515416/i-want-to-simply-subtract-elements-from-two-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!