把元素为tuple格式的(x,y)的list相互之间对应相加后取平均值,给出python代码
时间: 2023-06-09 07:05:02 浏览: 51
可以使用zip和sum函数来实现:
lst = [(1,2), (3,4), (5,6)]
avg = tuple(sum(x)/len(x) for x in zip(*lst))
print(avg) # 输出 (3.0, 4.0)
解释:
- zip(*lst) 将列表中的元组转化为元组中的列表 [(1,3,5), (2,4,6)]
- sum(x)/len(x) 计算元素 x 的平均值
- tuple(...) 将每个平均值转化为元组类型
相关问题
对于一组元素为tuple类型的(x,y)的list集合,怎么获取各个x,y组成的list的平均值,python代码
可以按照以下方式实现获取各个x,y组成的list的平均值:
```python
# sample datadata = [(1, 2), (3, 4), (5, 6)]
# initialize lists
list_x = []
list_y = []
# iterate through the tuples and append x and y to corresponding lists
for x, y in data:
list_x.append(x)
list_y.append(y)
# calculate average using sum() and len() functions
avg_x = sum(list_x) / len(list_x)
avg_y = sum(list_y) / len(list_y)
# print average values
print("Average of x values: ", avg_x)
print("Average of y values: ", avg_y)
```
这段代码的输出将为:
```
Average of x values: 3.0
Average of y values: 4.0
```
对于一个元素为tuple(x,y)的list,怎么求取所有元素对应的平均值,并输出成list
可以使用列表推导式和内置函数zip()来实现:
```python
lst = [(1, 2), (3, 4), (5, 6)]
avg_lst = [sum(pair)/len(pair) for pair in zip(*lst)]
print(avg_lst)
# 输出:[3.0, 4.0]
```
首先使用zip()函数将所有的x或y值分别组成一个元组,然后再遍历所有组成的元组进行求和和求平均值,生成一个包含结果的列表。