列表内容的平均值
我有一个如下所示的列表:
mylist = [('a', [(0,1), (1,2), (2,3)]),
('b', [(0,1), (1,2), (2,3)]),
('c', [(0,1), (1,2), (2,3)])]
这是我在代码中进行不同操作后得到的。
是否有可能得到如下所示的输出?
newlist = [('a', [0.5, 1.5, 2.5]),
('b', [0.5, 1.5, 2.5]),
('c', [0.5, 1.5, 2.5])]
输入列表的内容为范围,输出列表是通过取每个范围中两个数字的平均值生成的。谢谢。
I have a list like the following:
mylist = [('a', [(0,1), (1,2), (2,3)]),
('b', [(0,1), (1,2), (2,3)]),
('c', [(0,1), (1,2), (2,3)])]
which I got after different operations in the code.
Is it possible to get an output like the following?
newlist = [('a', [0.5, 1.5, 2.5]),
('b', [0.5, 1.5, 2.5]),
('c', [0.5, 1.5, 2.5])]
The input list has the contents as ranges and the output list is generated by taking the average of the two numbers from each range. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这适用于 Python 3;在 Python 2 中,您需要
这些列表推导式等价于以下更详细的代码:
This works in Python 3; in Python 2, you need
These list comprehensions are equivalent to the following, more verbose code:
列表推导式很好,但我最喜欢的 Python 技术是
map()
,它将函数应用于结构的每个元素:正如 Tim 所说,这适用于 Python 3,您需要一个
float(len(x))
对于 Python 2。List comprehensions are nice, but my favorite Pythonic technique is
map()
, which applies a function to every element of a structure:As Tim says, this works for Python 3, you'd need a
float(len(x))
for Python 2.要仅使用一个列表(有效的 python 部分),您可以使用列表理解:
这应该让您朝着正确的方向前进,并为您提供:
To work with just one of your lists (the valid python portion), you could use a list comprehension:
This should get you in the right direction, and gives you: