标签归档:sum

将两个LISTS的值之和添加到新的LIST中

问题:将两个LISTS的值之和添加到新的LIST中

我有以下两个列表:

first = [1,2,3,4,5]
second = [6,7,8,9,10]

现在,我想将这两个列表中的项目添加到新列表中。

输出应该是

third = [7,9,11,13,15]

I have the following two lists:

first = [1,2,3,4,5]
second = [6,7,8,9,10]

Now I want to add the items from both of these lists into a new list.

output should be

third = [7,9,11,13,15]

回答 0

zip功能在此处有用,可与列表推导一起使用。

[x + y for x, y in zip(first, second)]

如果您有一个列表列表(而不是两个列表):

lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]

The zip function is useful here, used with a list comprehension.

[x + y for x, y in zip(first, second)]

If you have a list of lists (instead of just two lists):

lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]

回答 1

来自文档

import operator
list(map(operator.add, first,second))

From docs

import operator
list(map(operator.add, first,second))

回答 2

假设两个列表a,并b具有相同的长度,你不需要压缩,numpy的或其他任何东西。

Python 2.x和3.x:

[a[i]+b[i] for i in range(len(a))]

Assuming both lists a and b have same length, you do not need zip, numpy or anything else.

Python 2.x and 3.x:

[a[i]+b[i] for i in range(len(a))]

回答 3

numpy中的默认行为是逐组件添加

import numpy as np
np.add(first, second)

哪个输出

array([7,9,11,13,15])

Default behavior in numpy is add componentwise

import numpy as np
np.add(first, second)

which outputs

array([7,9,11,13,15])

回答 4

这可以扩展到任意数量的列表:

[sum(sublist) for sublist in itertools.izip(*myListOfLists)]

在你的情况下,myListOfLists[first, second]

This extends itself to any number of lists:

[sum(sublist) for sublist in itertools.izip(*myListOfLists)]

In your case, myListOfLists would be [first, second]


回答 5

尝试以下代码:

first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))

Try the following code:

first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))

回答 6

执行此操作的简单方法和快速方法是:

three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

另外,您可以使用numpy sum:

from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])

The easy way and fast way to do this is:

three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

Alternatively, you can use numpy sum:

from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])

回答 7

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = map(lambda x,y: x+y,first,second)
print three



Output 
[7, 9, 11, 13, 15]
first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = map(lambda x,y: x+y,first,second)
print three



Output 
[7, 9, 11, 13, 15]

回答 8

一线解决方案

list(map(lambda x,y: x+y, a,b))

one-liner solution

list(map(lambda x,y: x+y, a,b))

回答 9

Thiru在3月17日9:25回答了我的问题。

这更加简单快捷,这是他的解决方案:

执行此操作的简单方法和快速方法是:

 three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

另外,您可以使用numpy sum:

 from numpy import sum
 three = sum([first,second], axis=0) # array([7,9,11,13,15])

您需要numpy!

numpy数组可以做一些像矢量的操作

import numpy as np
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = list(np.array(a) + np.array(b))
print c
# [7, 9, 11, 13, 15]

My answer is repeated with Thiru’s that answered it in Mar 17 at 9:25.

It was simpler and quicker, here are his solutions:

The easy way and fast way to do this is:

 three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

Alternatively, you can use numpy sum:

 from numpy import sum
 three = sum([first,second], axis=0) # array([7,9,11,13,15])

You need numpy!

numpy array could do some operation like vectors
import numpy as np
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = list(np.array(a) + np.array(b))
print c
# [7, 9, 11, 13, 15]

回答 10

如果未知数量的相同长度的列表,则可以使用以下功能。

在这里,* args接受可变数量的列表参数(但每个参数仅求和相同数量的元素)。再次使用*来解压缩每个列表中的元素。

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

输出:

[2, 4, 6]

或有3个清单

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

输出:

[19, 19, 19, 19, 19]

If you have an unknown number of lists of the same length, you can use the below function.

Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each). The * is used again to unpack the elements in each of the lists.

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

Output:

[2, 4, 6]

Or with 3 lists

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

Output:

[19, 19, 19, 19, 19]

回答 11

您可以使用zip(),将两个数组“交织”在一起,然后使用map(),它将对一个可迭代对象中的每个元素应用一个函数:

>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> zip(a, b)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> map(lambda x: x[0] + x[1], zip(a, b))
[7, 9, 11, 13, 15]

You can use zip(), which will “interleave” the two arrays together, and then map(), which will apply a function to each element in an iterable:

>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> zip(a, b)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> map(lambda x: x[0] + x[1], zip(a, b))
[7, 9, 11, 13, 15]

回答 12

这是另一种方法。我们利用python的内部__add__函数:

class SumList(object):
    def __init__(self, this_list):
        self.mylist = this_list

    def __add__(self, other):
        new_list = []
        zipped_list = zip(self.mylist, other.mylist)
        for item in zipped_list:
            new_list.append(item[0] + item[1])
        return SumList(new_list)

    def __repr__(self):
        return str(self.mylist)

list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)

输出量

[11, 22, 33, 44, 55]

Here is another way to do it. We make use of the internal __add__ function of python:

class SumList(object):
    def __init__(self, this_list):
        self.mylist = this_list

    def __add__(self, other):
        new_list = []
        zipped_list = zip(self.mylist, other.mylist)
        for item in zipped_list:
            new_list.append(item[0] + item[1])
        return SumList(new_list)

    def __repr__(self):
        return str(self.mylist)

list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)

Output

[11, 22, 33, 44, 55]

回答 13

如果您还想添加列表中的其余值,则可以使用它(在Python3.5中有效)

def addVectors(v1, v2):
    sum = [x + y for x, y in zip(v1, v2)]
    if not len(v1) >= len(v2):
        sum += v2[len(v1):]
    else:
        sum += v1[len(v2):]

    return sum


#for testing 
if __name__=='__main__':
    a = [1, 2]
    b = [1, 2, 3, 4]
    print(a)
    print(b)
    print(addVectors(a,b))

If you want to add also the rest of the values in the lists you can use this (this is working in Python3.5)

def addVectors(v1, v2):
    sum = [x + y for x, y in zip(v1, v2)]
    if not len(v1) >= len(v2):
        sum += v2[len(v1):]
    else:
        sum += v1[len(v2):]

    return sum


#for testing 
if __name__=='__main__':
    a = [1, 2]
    b = [1, 2, 3, 4]
    print(a)
    print(b)
    print(addVectors(a,b))

回答 14

    first = [1,2,3,4,5]
    second = [6,7,8,9,10]
    #one way
    third = [x + y for x, y in zip(first, second)]
    print("third" , third) 
    #otherway
    fourth = []
    for i,j in zip(first,second):
        global fourth
        fourth.append(i + j)
    print("fourth" , fourth )
#third [7, 9, 11, 13, 15]
#fourth [7, 9, 11, 13, 15]
    first = [1,2,3,4,5]
    second = [6,7,8,9,10]
    #one way
    third = [x + y for x, y in zip(first, second)]
    print("third" , third) 
    #otherway
    fourth = []
    for i,j in zip(first,second):
        global fourth
        fourth.append(i + j)
    print("fourth" , fourth )
#third [7, 9, 11, 13, 15]
#fourth [7, 9, 11, 13, 15]

回答 15

这是另一种方法。它对我来说很好。

N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]

for i in range(0,N):
  sum.append(num1[i]+num2[i])

for element in sum:
  print(element, end=" ")

print("")

Here is another way to do it.It is working fine for me .

N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]

for i in range(0,N):
  sum.append(num1[i]+num2[i])

for element in sum:
  print(element, end=" ")

print("")

回答 16

j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]
j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]

回答 17

也许是最简单的方法:

first = [1,2,3,4,5]
second = [6,7,8,9,10]
three=[]

for i in range(0,5):
    three.append(first[i]+second[i])

print(three)

Perhaps the simplest approach:

first = [1,2,3,4,5]
second = [6,7,8,9,10]
three=[]

for i in range(0,5):
    three.append(first[i]+second[i])

print(three)

回答 18

如果您将列表视为numpy数组,则需要轻松对其求和:

import numpy as np

third = np.array(first) + np.array(second)

print third

[7, 9, 11, 13, 15]

If you consider your lists as numpy array, then you need to easily sum them:

import numpy as np

third = np.array(first) + np.array(second)

print third

[7, 9, 11, 13, 15]

回答 19

如果您有不同长度的列表怎么办,那么您可以尝试这样的操作(使用zip_longest

from itertools import zip_longest  # izip_longest for python2.x

l1 = [1, 2, 3]
l2 = [4, 5, 6, 7]

>>> list(map(sum, zip_longest(l1, l2, fillvalue=0)))
[5, 7, 9, 7]

What if you have list with different length, then you can try something like this (using zip_longest)

from itertools import zip_longest  # izip_longest for python2.x

l1 = [1, 2, 3]
l2 = [4, 5, 6, 7]

>>> list(map(sum, zip_longest(l1, l2, fillvalue=0)))
[5, 7, 9, 7]

回答 20

您可以使用此方法,但仅当两个列表的大小相同时,该方法才有效:

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
third = []

a = len(first)
b = int(0)
while True:
    x = first[b]
    y = second[b]
    ans = x + y
    third.append(ans)
    b = b + 1
    if b == a:
        break

print third

You can use this method but it will work only if both the list are of the same size:

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
third = []

a = len(first)
b = int(0)
while True:
    x = first[b]
    y = second[b]
    ans = x + y
    third.append(ans)
    b = b + 1
    if b == a:
        break

print third

获取总计熊猫列

问题:获取总计熊猫列

目标

我有一个Pandas数据框,如下所示,具有多个列,并希望获取列的总数MyColumn


数据框df

print df

           X           MyColumn  Y              Z   
0          A           84        13.0           69.0   
1          B           76         77.0          127.0   
2          C           28         69.0           16.0   
3          D           28         28.0           31.0   
4          E           19         20.0           85.0   
5          F           84        193.0           70.0   

我的尝试

我试图使用groupby和获得列的总和.sum()

Total = df.groupby['MyColumn'].sum()

print Total

这将导致以下错误:

TypeError: 'instancemethod' object has no attribute '__getitem__'

预期Yield

我期望输出如下:

319

或者,我想df用一个包含总数的新row标题进行编辑TOTAL

           X           MyColumn  Y              Z   
0          A           84        13.0           69.0   
1          B           76         77.0          127.0   
2          C           28         69.0           16.0   
3          D           28         28.0           31.0   
4          E           19         20.0           85.0   
5          F           84        193.0           70.0   
TOTAL                  319

Target

I have a Pandas data frame, as shown below, with multiple columns and would like to get the total of column, MyColumn.


Data Framedf:

print df

           X           MyColumn  Y              Z   
0          A           84        13.0           69.0   
1          B           76         77.0          127.0   
2          C           28         69.0           16.0   
3          D           28         28.0           31.0   
4          E           19         20.0           85.0   
5          F           84        193.0           70.0   

My attempt:

I have attempted to get the sum of the column using groupby and .sum():

Total = df.groupby['MyColumn'].sum()

print Total

This causes the following error:

TypeError: 'instancemethod' object has no attribute '__getitem__'

Expected Output

I’d have expected the output to be as followed:

319

Or alternatively, I would like df to be edited with a new row entitled TOTAL containing the total:

           X           MyColumn  Y              Z   
0          A           84        13.0           69.0   
1          B           76         77.0          127.0   
2          C           28         69.0           16.0   
3          D           28         28.0           31.0   
4          E           19         20.0           85.0   
5          F           84        193.0           70.0   
TOTAL                  319

回答 0

您应该使用sum

Total = df['MyColumn'].sum()
print (Total)
319

然后loc与一起使用Series,在这种情况下,索引应设置为与您需要求和的特定列相同:

df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index = ['MyColumn'])
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

因为如果传递标量,则将填充所有行的值:

df.loc['Total'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A        84   13.0   69.0
1        B        76   77.0  127.0
2        C        28   69.0   16.0
3        D        28   28.0   31.0
4        E        19   20.0   85.0
5        F        84  193.0   70.0
Total  319       319  319.0  319.0

另有两个解决方案atix请参见下面的应用程序:

df.at['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

df.ix['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

注意:自Pandas v0.20起,ix已弃用。使用lociloc代替。

You should use sum:

Total = df['MyColumn'].sum()
print (Total)
319

Then you use loc with Series, in that case the index should be set as the same as the specific column you need to sum:

df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index = ['MyColumn'])
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

because if you pass scalar, the values of all rows will be filled:

df.loc['Total'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A        84   13.0   69.0
1        B        76   77.0  127.0
2        C        28   69.0   16.0
3        D        28   28.0   31.0
4        E        19   20.0   85.0
5        F        84  193.0   70.0
Total  319       319  319.0  319.0

Two other solutions are with at, and ix see the applications below:

df.at['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

df.ix['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

Note: Since Pandas v0.20, ix has been deprecated. Use loc or iloc instead.


回答 1

您可以在此处使用的另一种选择:

df.loc["Total", "MyColumn"] = df.MyColumn.sum()

#         X  MyColumn      Y       Z
#0        A     84.0    13.0    69.0
#1        B     76.0    77.0   127.0
#2        C     28.0    69.0    16.0
#3        D     28.0    28.0    31.0
#4        E     19.0    20.0    85.0
#5        F     84.0   193.0    70.0
#Total  NaN    319.0     NaN     NaN

您也可以使用append()方法:

df.append(pd.DataFrame(df.MyColumn.sum(), index = ["Total"], columns=["MyColumn"]))


更新:

如果需要为所有数字列追加总和,则可以执行以下操作之一:

用于append以功能性方式执行此操作(不更改原始数据帧):

# select numeric columns and calculate the sums
sums = df.select_dtypes(pd.np.number).sum().rename('total')

# append sums to the data frame
df.append(sums)
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     319.0  400.0  398.0

用于loc在适当位置更改数据框:

df.loc['total'] = df.select_dtypes(pd.np.number).sum()
df
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     638.0  800.0  796.0

Another option you can go with here:

df.loc["Total", "MyColumn"] = df.MyColumn.sum()

#         X  MyColumn      Y       Z
#0        A     84.0    13.0    69.0
#1        B     76.0    77.0   127.0
#2        C     28.0    69.0    16.0
#3        D     28.0    28.0    31.0
#4        E     19.0    20.0    85.0
#5        F     84.0   193.0    70.0
#Total  NaN    319.0     NaN     NaN

You can also use append() method:

df.append(pd.DataFrame(df.MyColumn.sum(), index = ["Total"], columns=["MyColumn"]))


Update:

In case you need to append sum for all numeric columns, you can do one of the followings:

Use append to do this in a functional manner (doesn’t change the original data frame):

# select numeric columns and calculate the sums
sums = df.select_dtypes(pd.np.number).sum().rename('total')

# append sums to the data frame
df.append(sums)
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     319.0  400.0  398.0

Use loc to mutate data frame in place:

df.loc['total'] = df.select_dtypes(pd.np.number).sum()
df
#         X  MyColumn      Y      Z
#0        A      84.0   13.0   69.0
#1        B      76.0   77.0  127.0
#2        C      28.0   69.0   16.0
#3        D      28.0   28.0   31.0
#4        E      19.0   20.0   85.0
#5        F      84.0  193.0   70.0
#total  NaN     638.0  800.0  796.0

回答 2

与获取数据框的长度类似len(df),以下内容适用于熊猫和大火:

Total = sum(df['MyColumn'])

或者

Total = sum(df.MyColumn)
print Total

Similar to getting the length of a dataframe, len(df), the following worked for pandas and blaze:

Total = sum(df['MyColumn'])

or alternatively

Total = sum(df.MyColumn)
print Total

回答 3

列求和有两种方法

数据集= pd.read_csv(“ data.csv”)

1:总和(dataset.Column_name)

2:数据集[‘Column_Name’]。sum()

如果有任何问题,请纠正我。

There are two ways to sum of a column

dataset = pd.read_csv(“data.csv”)

1: sum(dataset.Column_name)

2: dataset[‘Column_Name’].sum()

If there is any issue in this the please correct me..


回答 4

作为其他选择,您可以执行以下操作

Group   Valuation   amount
    0   BKB Tube    156
    1   BKB Tube    143
    2   BKB Tube    67
    3   BAC Tube    176
    4   BAC Tube    39
    5   JDK Tube    75
    6   JDK Tube    35
    7   JDK Tube    155
    8   ETH Tube    38
    9   ETH Tube    56

下面的脚本,您可以用于上面的数据

import pandas as pd    
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()

As other option, you can do something like below

Group   Valuation   amount
    0   BKB Tube    156
    1   BKB Tube    143
    2   BKB Tube    67
    3   BAC Tube    176
    4   BAC Tube    39
    5   JDK Tube    75
    6   JDK Tube    35
    7   JDK Tube    155
    8   ETH Tube    38
    9   ETH Tube    56

Below script, you can use for above data

import pandas as pd    
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()

熊猫:求和给定列的DataFrame行

问题:熊猫:求和给定列的DataFrame行

我有以下DataFrame:

In [1]:

import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df
Out [1]:
   a  b   c  d
0  1  2  dd  5
1  2  3  ee  9
2  3  4  ff  1

我想增加一列'e'是列的总和'a''b''d'

在各个论坛上,我认为这样会起作用:

df['e'] = df[['a','b','d']].map(sum)

但事实并非如此。

我想知道适当的操作与列的列表['a','b','d']df作为输入。

I have the following DataFrame:

In [1]:

import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df
Out [1]:
   a  b   c  d
0  1  2  dd  5
1  2  3  ee  9
2  3  4  ff  1

I would like to add a column 'e' which is the sum of column 'a', 'b' and 'd'.

Going across forums, I thought something like this would work:

df['e'] = df[['a','b','d']].map(sum)

But it didn’t.

I would like to know the appropriate operation with the list of columns ['a','b','d'] and df as inputs.


回答 0

您可以sum设置参数axis=1以对行求和,这将忽略任何数字列:

In [91]:

df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

如果您只想汇总特定的列,则可以创建列的列表并删除不感兴趣的列:

In [98]:

col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:

df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
   a  b   c  d  e
0  1  2  dd  5  3
1  2  3  ee  9  5
2  3  4  ff  1  7

You can just sum and set param axis=1 to sum the rows, this will ignore none numeric columns:

In [91]:

df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:

In [98]:

col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:

df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
   a  b   c  d  e
0  1  2  dd  5  3
1  2  3  ee  9  5
2  3  4  ff  1  7

回答 1

如果您只需要汇总几列,则可以编写:

df['e'] = df['a'] + df['b'] + df['d']

这将创建e具有以下值的新列:

   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

对于较长的列列表,首选EdChum的答案。

If you have just a few columns to sum, you can write:

df['e'] = df['a'] + df['b'] + df['d']

This creates new column e with the values:

   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

For longer lists of columns, EdChum’s answer is preferred.


回答 2

创建要添加的列名列表。

df['total']=df.loc[:,list_name].sum(axis=1)

如果要某些行的总和,请使用“:”指定行

Create a list of column names you want to add up.

df['total']=df.loc[:,list_name].sum(axis=1)

If you want the sum for certain rows, specify the rows using ‘:’


回答 3

这是使用iloc选择要累加的列的更简单方法:

df['f']=df.iloc[:,0:2].sum(axis=1)
df['g']=df.iloc[:,[0,1]].sum(axis=1)
df['h']=df.iloc[:,[0,3]].sum(axis=1)

生成:

   a  b   c  d   e  f  g   h
0  1  2  dd  5   8  3  3   6
1  2  3  ee  9  14  5  5  11
2  3  4  ff  1   8  7  7   4

我找不到一种将范围和特定列结合起来的方法,例如:

df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
df['i']=df.iloc[:,[0:2,3]].sum(axis=1)

This is a simpler way using iloc to select which columns to sum:

df['f']=df.iloc[:,0:2].sum(axis=1)
df['g']=df.iloc[:,[0,1]].sum(axis=1)
df['h']=df.iloc[:,[0,3]].sum(axis=1)

Produces:

   a  b   c  d   e  f  g   h
0  1  2  dd  5   8  3  3   6
1  2  3  ee  9  14  5  5  11
2  3  4  ff  1   8  7  7   4

I can’t find a way to combine a range and specific columns that works e.g. something like:

df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
df['i']=df.iloc[:,[0:2,3]].sum(axis=1)

回答 4

当我按顺序排列列时,以下语法对我有帮助

awards_frame.values[:,1:4].sum(axis =1)

Following syntax helped me when I have columns in sequence

awards_frame.values[:,1:4].sum(axis =1)

回答 5

您只需将数据框传递给以下函数即可

def sum_frame_by_column(frame, new_col_name, list_of_cols_to_sum):
    frame[new_col_name] = frame[list_of_cols_to_sum].astype(float).sum(axis=1)
    return(frame)

范例

我有一个数据框(awards_frame)如下:

…并且我想创建一个新列,显示每一行的奖励总和

用法

我只是通过我的awards_frame进入功能,同时指定名称的新列的,和列表将被归纳列名:

sum_frame_by_column(awards_frame, 'award_sum', ['award_1','award_2','award_3'])

结果

You can simply pass your dataframe into the following function:

def sum_frame_by_column(frame, new_col_name, list_of_cols_to_sum):
    frame[new_col_name] = frame[list_of_cols_to_sum].astype(float).sum(axis=1)
    return(frame)

Example:

I have a dataframe (awards_frame) as follows:

…and I want to create a new column that shows the sum of awards for each row:

Usage:

I simply pass my awards_frame into the function, also specifying the name of the new column, and a list of column names that are to be summed:

sum_frame_by_column(awards_frame, 'award_sum', ['award_1','award_2','award_3'])

Result:


回答 6

这里最简单的方法是使用

    df.eval('e = a + b + d')

The shortest and simpliest way here is to use

    df.eval('e = a + b + d')

如何对字典中的所有值求和?

问题:如何对字典中的所有值求和?

假设我有一本字典,其中的键映射为整数,例如:

d = {'key1': 1,'key2': 14,'key3': 47}

是否有返回值的总和在语法上简约的方式d-即62在这种情况下?

Let’s say I have a dictionary in which the keys map to integers like:

d = {'key1': 1,'key2': 14,'key3': 47}

Is there a syntactically minimalistic way to return the sum of the values in d—i.e. 62 in this case?


回答 0

如您所料:

sum(d.values())

As you’d expect:

sum(d.values())

回答 1

在Python 2中,您可以避免通过使用itervalues()dictionary方法创建所有值的临时副本,该方法返回字典键的迭代器:

sum(d.itervalues())

在Python 3中,您只能使用d.values()该方法,因为该方法已更改为可以这样做(并且itervalues()由于不再需要而被删除)。

为了使编写总是在字典键值上进行迭代的版本无关代码更容易,实用程序功能可能会有所帮助:

import sys

def itervalues(d):
    return iter(getattr(d, ('itervalues', 'values')[sys.version_info[0]>2])())

sum(itervalues(d))

这本质上就是本杰明·彼得森的six模块所做的。

In Python 2 you can avoid making a temporary copy of all the values by using the itervalues() dictionary method, which returns an iterator of the dictionary’s keys:

sum(d.itervalues())

In Python 3 you can just use d.values() because that method was changed to do that (and itervalues() was removed since it was no longer needed).

To make it easier to write version independent code which always iterates over the values of the dictionary’s keys, a utility function can be helpful:

import sys

def itervalues(d):
    return iter(getattr(d, ('itervalues', 'values')[sys.version_info[0]>2])())

sum(itervalues(d))

This is essentially what Benjamin Peterson’s six module does.


回答 2

当然可以。这是一种汇总字典值的方法。

>>> d = {'key1':1,'key2':14,'key3':47}
>>> sum(d.values())
62

Sure there is. Here is a way to sum the values of a dictionary.

>>> d = {'key1':1,'key2':14,'key3':47}
>>> sum(d.values())
62

回答 3

d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)
print(sum1)

你可以使用for循环

d = {'key1': 1,'key2': 14,'key3': 47}
sum1 = sum(d[item] for item in d)
print(sum1)

you can do it using the for loop


回答 4

我觉得这sum(d.values())是获得总和的最有效方法。

您也可以尝试用reduce函数来计算总和以及lambda表达式:

reduce(lambda x,y:x+y,d.values())

I feel sum(d.values()) is the most efficient way to get the sum.

You can also try the reduce function to calculate the sum along with a lambda expression:

reduce(lambda x,y:x+y,d.values())

回答 5

sum(d.values())-“ d”->您的字典变量

sum(d.values()) – “d” -> Your dictionary Variable


回答 6

phihag的答案(和类似的答案)在python3中不起作用。

对于python 3:

d = {'key1': 1,'key2': 14,'key3': 47}
sum(list(d.values()))

更新!有人抱怨说这行不通!我只是在终端上附上截图。可能是版本不匹配等。

phihag’s answer (and similar ones) won’t work in python3.

For python 3:

d = {'key1': 1,'key2': 14,'key3': 47}
sum(list(d.values()))

Update! There are complains that it doesn’t work! I just attach a screenshot from my terminal. Could be some mismatch in versions etc.


回答 7

您可以为此考虑“ for循环”:

  d = {'data': 100, 'data2': 200, 'data3': 500}
  total = 0
  for i in d.values():
        total += i

总计= 800

You could consider ‘for loop’ for this:

  d = {'data': 100, 'data2': 200, 'data3': 500}
  total = 0
  for i in d.values():
        total += i

total = 800


回答 8

您可以获取字典中所有值的生成器,然后将其转换为列表,然后使用sum()函数获取所有值的总和。

例:

c={"a":123,"b":4,"d":4,"c":-1001,"x":2002,"y":1001}

sum(list(c.values()))

You can get a generator of all the values in the dictionary, then cast it to a list and use the sum() function to get the sum of all the values.

Example:

c={"a":123,"b":4,"d":4,"c":-1001,"x":2002,"y":1001}

sum(list(c.values()))

对Python中的数字列表求和

问题:对Python中的数字列表求和

我有一个数字列表,例如[1,2,3,4,5...],我想计算(1+2)/2第二个,(2+3)/2第三个, (3+4)/2等等。我怎样才能做到这一点?

我想将第一个数字与第二个数字相加并除以2,然后将第二个数字与第三个数字相加并除以2,依此类推。

另外,如何求和数字列表?

a = [1, 2, 3, 4, 5, ...]

是吗:

b = sum(a)
print b

得到一个号码?

这对我不起作用。

I have a list of numbers such as [1,2,3,4,5...], and I want to calculate (1+2)/2 and for the second, (2+3)/2 and the third, (3+4)/2, and so on. How can I do that?

I would like to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on.

Also, how can I sum a list of numbers?

a = [1, 2, 3, 4, 5, ...]

Is it:

b = sum(a)
print b

to get one number?

This doesn’t work for me.


回答 0

问题1:因此,您想要(元素0 +元素1)/ 2,(元素1 +元素2)/ 2,…等等。

我们列出两个列表:除第一个元素之外的每个元素中的一个,除最后一个元素之外的每个元素中的一个。然后,我们想要的平均值是从两个列表中得出的每对平均值。我们zip过去常常从两个列表中取对。

我假设即使输入值是整数,您也希望在结果中看到小数。默认情况下,Python会进行整数除法:它会丢弃余数。要完全划分事物,我们需要使用浮点数。幸运的是,将int除以浮点数将产生一个浮点数,因此我们仅将其2.0用作除数而不是2

从而:

averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]

问题2:

的使用sum应该可以正常工作。以下作品:

a = range(10)
# [0,1,2,3,4,5,6,7,8,9]
b = sum(a)
print b
# Prints 45

同样,您不需要在此过程的每一步都将所有内容分配给变量。print sum(a)效果很好。

您将必须更确切地确切地写出您所写的内容以及它是如何工作的。

Question 1: So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, … etc.

We make two lists: one of every element except the first, and one of every element except the last. Then the averages we want are the averages of each pair taken from the two lists. We use zip to take pairs from two lists.

I assume you want to see decimals in the result, even though your input values are integers. By default, Python does integer division: it discards the remainder. To divide things through all the way, we need to use floating-point numbers. Fortunately, dividing an int by a float will produce a float, so we just use 2.0 for our divisor instead of 2.

Thus:

averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]

Question 2:

That use of sum should work fine. The following works:

a = range(10)
# [0,1,2,3,4,5,6,7,8,9]
b = sum(a)
print b
# Prints 45

Also, you don’t need to assign everything to a variable at every step along the way. print sum(a) works just fine.

You will have to be more specific about exactly what you wrote and how it isn’t working.


回答 1

总数列表:

sum(list_of_nums)

使用列表推导计算n和n-1的一半(如果我的模式正确):

[(x + (x - 1)) / 2 for x in list_of_nums]

对相邻元素求和,例如((1 + 2)/ 2)+((2 + 3)/ 2)+ …使用reducelambda

reduce(lambda x, y: (x + y) / 2, list_of_nums)

Sum list of numbers:

sum(list_of_nums)

Calculating half of n and n – 1 (if I have the pattern correct), using a list comprehension:

[(x + (x - 1)) / 2 for x in list_of_nums]

Sum adjacent elements, e.g. ((1 + 2) / 2) + ((2 + 3) / 2) + … using reduce and lambdas

reduce(lambda x, y: (x + y) / 2, list_of_nums)

回答 2

问题2: 总结一个整数列表:

a = [2, 3, 5, 8]
sum(a)
# 18
# or you can do:
sum(i for i in a)
# 18

如果列表包含整数作为字符串:

a = ['5', '6']
# import Decimal: from decimal import Decimal
sum(Decimal(i) for i in a)

Question 2: To sum a list of integers:

a = [2, 3, 5, 8]
sum(a)
# 18
# or you can do:
sum(i for i in a)
# 18

If the list contains integers as strings:

a = ['5', '6']
# import Decimal: from decimal import Decimal
sum(Decimal(i) for i in a)

回答 3

您可以这样尝试:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sm = sum(a[0:len(a)]) # Sum of 'a' from 0 index to 9 index. sum(a) == sum(a[0:len(a)]
print(sm) # Python 3
print sm  # Python 2

You can try this way:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sm = sum(a[0:len(a)]) # Sum of 'a' from 0 index to 9 index. sum(a) == sum(a[0:len(a)]
print(sm) # Python 3
print sm  # Python 2

回答 4

>>> a = range(10)
>>> sum(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del sum
>>> sum(a)
45

似乎sum已经在代码中的某个地方定义了该代码,并覆盖了默认功能。所以我删除了它,问题解决了。

>>> a = range(10)
>>> sum(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del sum
>>> sum(a)
45

It seems that sum has been defined in the code somewhere and overwrites the default function. So I deleted it and the problem was solved.


回答 5

使用简单list-comprehensionsum

>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5

Using a simple list-comprehension and the sum:

>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5

回答 6

所有答案均显示出程序化和通用的方法。我建议针对您的情况的数学方法。特别是对于长列表,它可能会更快。之所以有效,是因为您的列表是一个自然数列表,最多可包含n

假设我们有自然数1, 2, 3, ..., 10

>>> nat_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

您可以sum在列表中使用该功能:

>>> print sum(nat_seq)
55

您还可以使用公式n*(n+1)/2where n是列表中最后一个元素的值(此处nat_seq[-1]:),因此可以避免迭代元素:

>>> print (nat_seq[-1]*(nat_seq[-1]+1))/2
55

要生成序列(1+2)/2, (2+3)/2, ..., (9+10)/2,可以使用生成器和公式(2*k-1)/2.(注意点使值成为浮点)。生成新列表时,您必须跳过第一个元素:

>>> new_seq = [(2*k-1)/2. for k in nat_seq[1:]]
>>> print new_seq
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

您也可以sum在此列表中使用该函数:

>>> print sum(new_seq)
49.5

但是您也可以使用公式(((n*2+1)/2)**2-1)/2,因此可以避免迭代元素:

>>> print (((new_seq[-1]*2+1)/2)**2-1)/2
49.5

All answers did show a programmatic and general approach. I suggest a mathematical approach specific for your case. It can be faster in particular for long lists. It works because your list is a list of natural numbers up to n:

Let’s assume we have the natural numbers 1, 2, 3, ..., 10:

>>> nat_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

You can use the sum function on a list:

>>> print sum(nat_seq)
55

You can also use the formula n*(n+1)/2 where n is the value of the last element in the list (here: nat_seq[-1]), so you avoid iterating over elements:

>>> print (nat_seq[-1]*(nat_seq[-1]+1))/2
55

To generate the sequence (1+2)/2, (2+3)/2, ..., (9+10)/2 you can use a generator and the formula (2*k-1)/2. (note the dot to make the values floating points). You have to skip the first element when generating the new list:

>>> new_seq = [(2*k-1)/2. for k in nat_seq[1:]]
>>> print new_seq
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

Here too, you can use the sum function on that list:

>>> print sum(new_seq)
49.5

But you can also use the formula (((n*2+1)/2)**2-1)/2, so you can avoid iterating over elements:

>>> print (((new_seq[-1]*2+1)/2)**2-1)/2
49.5

回答 7

解决此问题的最简单方法:

l =[1,2,3,4,5]
sum=0
for element in l:
    sum+=element
print sum

The simplest way to solve this problem:

l =[1,2,3,4,5]
sum=0
for element in l:
    sum+=element
print sum

回答 8

这个问题已经在这里回答

a = [1,2,3,4] sum(a)返回10

This question has been answered here

a = [1,2,3,4] sum(a) returns 10


回答 9

import numpy as np    
x = [1,2,3,4,5]
[(np.mean((x[i],x[i+1]))) for i in range(len(x)-1)]
# [1.5, 2.5, 3.5, 4.5]
import numpy as np    
x = [1,2,3,4,5]
[(np.mean((x[i],x[i+1]))) for i in range(len(x)-1)]
# [1.5, 2.5, 3.5, 4.5]

回答 10

生成器是编写此代码的简单方法:

from __future__ import division
# ^- so that 3/2 is 1.5 not 1

def averages( lst ):
    it = iter(lst) # Get a iterator over the list
    first = next(it)
    for item in it:
        yield (first+item)/2
        first = item

print list(averages(range(1,11)))
# [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

Generators are an easy way to write this:

from __future__ import division
# ^- so that 3/2 is 1.5 not 1

def averages( lst ):
    it = iter(lst) # Get a iterator over the list
    first = next(it)
    for item in it:
        yield (first+item)/2
        first = item

print list(averages(range(1,11)))
# [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

回答 11

让我们为初学者轻松:-

  1. global关键字将允许主函数内分配全局变量消息,而不产生新的本地变量
    message = "This is a global!"


def main():
    global message
    message = "This is a local"
    print(message)


main()
# outputs "This is a local" - From the Function call
print(message)
# outputs "This is a local" - From the Outer scope

这个概念叫做阴影

  1. 对Python中的数字列表求和
nums = [1, 2, 3, 4, 5]

var = 0


def sums():
    for num in nums:
        global var
        var = var + num
    print(var)


if __name__ == '__main__':
    sums()

输出= 15

Let us make it easy for Beginner:-

  1. The global keyword will allow the global variable message to be assigned within the main function without producing a new local variable
    message = "This is a global!"


def main():
    global message
    message = "This is a local"
    print(message)


main()
# outputs "This is a local" - From the Function call
print(message)
# outputs "This is a local" - From the Outer scope

This concept is called Shadowing

  1. Sum a list of numbers in Python
nums = [1, 2, 3, 4, 5]

var = 0


def sums():
    for num in nums:
        global var
        var = var + num
    print(var)


if __name__ == '__main__':
    sums()

Outputs = 15


回答 12

使用pairwise itertools配方

import itertools
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

def pair_averages(seq):
    return ( (a+b)/2 for a, b in pairwise(seq) )

Using the pairwise itertools recipe:

import itertools
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

def pair_averages(seq):
    return ( (a+b)/2 for a, b in pairwise(seq) )

回答 13

简短:

def ave(x,y):
  return (x + y) / 2.0

map(ave, a[:-1], a[1:])

外观如下:

>>> a = range(10)
>>> map(ave, a[:-1], a[1:])
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]

由于Python如何处理map两个以上的列表有些愚蠢,因此您必须截断该列表a[:-1]。如果您使用它,它的工作效果将超出您的预期itertools.imap

>>> import itertools
>>> itertools.imap(ave, a, a[1:])
<itertools.imap object at 0x1005c3990>
>>> list(_)
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]

Short and simple:

def ave(x,y):
  return (x + y) / 2.0

map(ave, a[:-1], a[1:])

And here’s how it looks:

>>> a = range(10)
>>> map(ave, a[:-1], a[1:])
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]

Due to some stupidity in how Python handles a map over two lists, you do have to truncate the list, a[:-1]. It works more as you’d expect if you use itertools.imap:

>>> import itertools
>>> itertools.imap(ave, a, a[1:])
<itertools.imap object at 0x1005c3990>
>>> list(_)
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]

回答 14

如此众多的解决方案,但我最喜欢的仍然缺失:

>>> import numpy as np
>>> arr = np.array([1,2,3,4,5])

numpy数组与列表没有太大区别(在这种情况下),除了可以将数组视为数字:

>>> ( arr[:-1] + arr[1:] ) / 2.0
[ 1.5  2.5  3.5  4.5]

做完了!

说明

花式索引的含义是:[1:]包括从1到末尾的所有元素(因此省略元素0),并且[:-1]是除最后一个元素之外的所有元素:

>>> arr[:-1]
array([1, 2, 3, 4])
>>> arr[1:]
array([2, 3, 4, 5])

因此,将这两个元素相加即可得到一个由元素(1 + 2),(2 + 3)等组成的数组。并不是说我要除以2.0,不是2因为否则Python会认为您仅使用整数并产生四舍五入的整数结果。

使用numpy的优势

NumPy的可快于各地的号码清单循环。根据列表的大小,速度快几个数量级。而且,它的代码少得多,至少对我来说,它更易于阅读。我正在尝试养成对所有数字组都使用numpy的习惯,这对我原本必须制作的所有循环和内部循环都是一个巨大的改进。

So many solutions, but my favourite is still missing:

>>> import numpy as np
>>> arr = np.array([1,2,3,4,5])

a numpy array is not too different from a list (in this use case), except that you can treat arrays like numbers:

>>> ( arr[:-1] + arr[1:] ) / 2.0
[ 1.5  2.5  3.5  4.5]

Done!

explanation

The fancy indices mean this: [1:] includes all elements from 1 to the end (thus omitting element 0), and [:-1] are all elements except the last one:

>>> arr[:-1]
array([1, 2, 3, 4])
>>> arr[1:]
array([2, 3, 4, 5])

So adding those two gives you an array consisting of elemens (1+2), (2+3) and so on. Not that I’m dividing by 2.0, not 2 because otherwise Python believes that you’re only using integers and produces rounded integer results.

advantage of using numpy

Numpy can be much faster than loops around lists of numbers. Depending on how big your list is, several orders of magnitude faster. Also, it’s a lot less code, and at least to me, it’s easier to read. I’m trying to make a habit out of using numpy for all groups of numbers, and it is a huge improvement to all the loops and lops-within-loops I would otherwise have had to make.


回答 15

我只是将lambda与map()一起使用

a = [1,2,3,4,5,6,7,8,9,10]
b = map(lambda x, y: (x+y)/2.0, fib[:-1], fib[1:])
print b

I’d just use a lambda with map()

a = [1,2,3,4,5,6,7,8,9,10]
b = map(lambda x, y: (x+y)/2.0, fib[:-1], fib[1:])
print b

回答 16

我使用while循环来获取结果:

i = 0
while i < len(a)-1:
   result = (a[i]+a[i+1])/2
   print result
   i +=1

I use a while loop to get the result:

i = 0
while i < len(a)-1:
   result = (a[i]+a[i+1])/2
   print result
   i +=1

回答 17

遍历列表中的元素并像这样更新总数:

def sum(a):
    total = 0
    index = 0
    while index < len(a):
        total = total + a[index]
        index = index + 1
    return total

Loop through elements in the list and update the total like this:

def sum(a):
    total = 0
    index = 0
    while index < len(a):
        total = total + a[index]
        index = index + 1
    return total

回答 18

多亏了Karl Knechtel,我才能够理解您的问题。我的解释:

  1. 您想要一个包含元素i和i + 1平均值的新列表。
  2. 您要对列表中的每个元素求和。

使用匿名函数(又名Lambda函数)的第一个问题:

s = lambda l: [(l[0]+l[1])/2.] + s(l[1:]) if len(l)>1 else []  #assuming you want result as float
s = lambda l: [(l[0]+l[1])//2] + s(l[1:]) if len(l)>1 else []  #assuming you want floor result

第二个问题也使用匿名函数(又名Lambda函数):

p = lambda l: l[0] + p(l[1:]) if l!=[] else 0

这两个问题合并在一行代码中:

s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0  #assuming you want result as float
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0  #assuming you want floor result

使用最适合您需求的那个

Thanks to Karl Knechtel i was able to understand your question. My interpretation:

  1. You want a new list with the average of the element i and i+1.
  2. You want to sum each element in the list.

First question using anonymous function (aka. Lambda function):

s = lambda l: [(l[0]+l[1])/2.] + s(l[1:]) if len(l)>1 else []  #assuming you want result as float
s = lambda l: [(l[0]+l[1])//2] + s(l[1:]) if len(l)>1 else []  #assuming you want floor result

Second question also using anonymous function (aka. Lambda function):

p = lambda l: l[0] + p(l[1:]) if l!=[] else 0

Both questions combined in a single line of code :

s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0  #assuming you want result as float
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0  #assuming you want floor result

use the one that fits best your needs


回答 19

您也可以使用递归进行相同的操作:

Python片段:

def sumOfArray(arr, startIndex):
    size = len(arr)
    if size == startIndex:  # To Check empty list
        return 0
    elif startIndex == (size - 1): # To Check Last Value
        return arr[startIndex]
    else:
        return arr[startIndex] + sumOfArray(arr, startIndex + 1)


print(sumOfArray([1,2,3,4,5], 0))

You can also do the same using recursion:

Python Snippet:

def sumOfArray(arr, startIndex):
    size = len(arr)
    if size == startIndex:  # To Check empty list
        return 0
    elif startIndex == (size - 1): # To Check Last Value
        return arr[startIndex]
    else:
        return arr[startIndex] + sumOfArray(arr, startIndex + 1)


print(sumOfArray([1,2,3,4,5], 0))

回答 20

尝试使用列表理解。就像是:

new_list = [(old_list[i] + old_list[i+1])/2 for i in range(len(old_list-1))]

Try using a list comprehension. Something like:

new_list = [(old_list[i] + old_list[i+1])/2 for i in range(len(old_list-1))]

回答 21

本着itertools的精神。成对配方的灵感。

from itertools import tee, izip

def average(iterable):
    "s -> (s0,s1)/2.0, (s1,s2)/2.0, ..."
    a, b = tee(iterable)
    next(b, None)
    return ((x+y)/2.0 for x, y in izip(a, b))

例子:

>>>list(average([1,2,3,4,5]))
[1.5, 2.5, 3.5, 4.5]
>>>list(average([1,20,31,45,56,0,0]))
[10.5, 25.5, 38.0, 50.5, 28.0, 0.0]
>>>list(average(average([1,2,3,4,5])))
[2.0, 3.0, 4.0]

In the spirit of itertools. Inspiration from the pairwise recipe.

from itertools import tee, izip

def average(iterable):
    "s -> (s0,s1)/2.0, (s1,s2)/2.0, ..."
    a, b = tee(iterable)
    next(b, None)
    return ((x+y)/2.0 for x, y in izip(a, b))

Examples:

>>>list(average([1,2,3,4,5]))
[1.5, 2.5, 3.5, 4.5]
>>>list(average([1,20,31,45,56,0,0]))
[10.5, 25.5, 38.0, 50.5, 28.0, 0.0]
>>>list(average(average([1,2,3,4,5])))
[2.0, 3.0, 4.0]

回答 22

n = int(input("Enter the length of array: "))
list1 = []
for i in range(n):
    list1.append(int(input("Enter numbers: ")))
print("User inputs are", list1)

list2 = []
for j in range(0, n-1):
    list2.append((list1[j]+list1[j+1])/2)
print("result = ", list2)
n = int(input("Enter the length of array: "))
list1 = []
for i in range(n):
    list1.append(int(input("Enter numbers: ")))
print("User inputs are", list1)

list2 = []
for j in range(0, n-1):
    list2.append((list1[j]+list1[j+1])/2)
print("result = ", list2)

回答 23

一种简单的方法是使用iter_tools排列

# If you are given a list

numList = [1,2,3,4,5,6,7]

# and you are asked to find the number of three sums that add to a particular number

target = 10
# How you could come up with the answer?

from itertools import permutations

good_permutations = []

for p in permutations(numList, 3):
    if sum(p) == target:
        good_permutations.append(p)

print(good_permutations)

结果是:

[(1, 2, 7), (1, 3, 6), (1, 4, 5), (1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 1, 7), (2, 3, 
5), (2, 5, 3), (2, 7, 1), (3, 1, 6), (3, 2, 5), (3, 5, 2), (3, 6, 1), (4, 1, 5), (4, 
5, 1), (5, 1, 4), (5, 2, 3), (5, 3, 2), (5, 4, 1), (6, 1, 3), (6, 3, 1), (7, 1, 2), 
(7, 2, 1)]

请注意,顺序很重要-意思是1、2、7也显示为2、1、7和7、1、2。您可以通过使用集合来减少此数目。

A simple way is to use the iter_tools permutation

# If you are given a list

numList = [1,2,3,4,5,6,7]

# and you are asked to find the number of three sums that add to a particular number

target = 10
# How you could come up with the answer?

from itertools import permutations

good_permutations = []

for p in permutations(numList, 3):
    if sum(p) == target:
        good_permutations.append(p)

print(good_permutations)

The result is:

[(1, 2, 7), (1, 3, 6), (1, 4, 5), (1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 1, 7), (2, 3, 
5), (2, 5, 3), (2, 7, 1), (3, 1, 6), (3, 2, 5), (3, 5, 2), (3, 6, 1), (4, 1, 5), (4, 
5, 1), (5, 1, 4), (5, 2, 3), (5, 3, 2), (5, 4, 1), (6, 1, 3), (6, 3, 1), (7, 1, 2), 
(7, 2, 1)]

Note that order matters – meaning 1, 2, 7 is also shown as 2, 1, 7 and 7, 1, 2. You can reduce this by using a set.


回答 24

在Python 3.8中,可以使用新的赋值运算符

>>> my_list = [1, 2, 3, 4, 5]
>>> itr = iter(my_list)
>>> a = next(itr)
>>> [(a + (a:=x))/2 for x in itr]
[1.5, 2.5, 3.5, 4.5]

a是对列表中前一个值的运行引用,因此将其初始化为列表的第一个元素,并且迭代在列表的其余部分进行,a并在每次迭代中使用后进行更新。

显式迭代器用于避免使用创建列表的副本my_list[1:]

In Python 3.8, the new assignment operator can be used

>>> my_list = [1, 2, 3, 4, 5]
>>> itr = iter(my_list)
>>> a = next(itr)
>>> [(a + (a:=x))/2 for x in itr]
[1.5, 2.5, 3.5, 4.5]

a is a running reference to the previous value in the list, hence it is initialized to the first element of the list and the iteration occurs over the rest of the list, updating a after it is used in each iteration.

An explicit iterator is used to avoid needing to create a copy of the list using my_list[1:].


回答 25

试试以下-

mylist = [1, 2, 3, 4]   

def add(mylist):
    total = 0
    for i in mylist:
        total += i
    return total

result = add(mylist)
print("sum = ", result)

Try the following –

mylist = [1, 2, 3, 4]   

def add(mylist):
    total = 0
    for i in mylist:
        total += i
    return total

result = add(mylist)
print("sum = ", result)