如何在 Python 的元组列表中对每个元组中的第一个值求和?

2023-08-31Python开发问题
5

本文介绍了如何在 Python 的元组列表中对每个元组中的第一个值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个这样的元组列表(总是对):

[(0, 1), (2, 3), (5, 7), (2, 1)]

我想找到每对中第一项的总和,即:

0 + 2 + 5 + 2

如何在 Python 中做到这一点?目前我正在遍历列表:

sum = 0对于 list_of_pairs 中的对:总和 += 对[0]

我觉得肯定有一种更 Pythonic 的方式.

解决方案

在 Python 的现代版本中,我建议 SilentGhost 发布的内容(为了清楚起见在此重复):

<块引用>

sum(i for i, j in list_of_pairs)


在此答案的早期版本中,我曾建议这样做,这是必要的,因为 SilentGhost 的版本在当时最新的 Python (2.3) 版本中不起作用:

sum([pair[0] for list_of_pairs])

现在那个版本的 Python 已经过时了,而且 SilentGhost 的代码适用于所有当前维护的 Python 版本,所以不再有任何理由推荐我最初发布的版本.

I have a list of tuples (always pairs) like this:

[(0, 1), (2, 3), (5, 7), (2, 1)]

I'd like to find the sum of the first items in each pair, i.e.:

0 + 2 + 5 + 2

How can I do this in Python? At the moment I'm iterating through the list:

sum = 0
for pair in list_of_pairs:
   sum += pair[0]

I have a feeling there must be a more Pythonic way.

解决方案

In modern versions of Python I'd suggest what SilentGhost posted (repeating here for clarity):

sum(i for i, j in list_of_pairs)


In an earlier version of this answer I had suggested this, which was necessary because SilentGhost's version didn't work in the version of Python (2.3) that was current at the time:

sum([pair[0] for pair in list_of_pairs])

Now that version of Python is beyond obsolete, and SilentGhost's code works in all currently-maintained versions of Python, so there's no longer any reason to recommend the version I had originally posted.

这篇关于如何在 Python 的元组列表中对每个元组中的第一个值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10