Python 在 for 循环之外获取修改后的列表

标签 python list for-loop tuples

我一直在研究一种制作元组列表并计算每个元组平均值的方法。

myList = [(1,2,3),(4,12,6)]
def GS(myList):
     for miniList in myList:
          r = miniList[0]
          g = miniList[1]
          b = miniList[2]
          GS = round((r+g+b)/3,2)
          miniList = list(miniList)
          miniList[0] = GS
          miniList[1] = GS
          miniList[2] = GS
          miniList = tuple(miniList)
     return myList     

 print(GS(myList))

我的列表是 [(1,2,3),(4,12,6)]

我应该得到每个元组的平均值并替换三个

输出:[(2.0,2.0,2.0),(7.33,7.33,7.33)]

最佳答案

您可以使用列表理解。下面是一个示例,它避免通过 mapzip 迭代器计算每个元组的长度两次。

myList = [(1,2,3),(4,12,6)]

def GS(L):
    lens = map(len, L)
    res = [(sum(i)/i_len,)*i_len for i, i_len in zip(L, lens)]
    return res

print(GS(myList))

[(2.0, 2.0, 2.0), (7.333333333333333, 7.333333333333333, 7.333333333333333)]

如果你想舍入小数,你可以使用:

res = [(round(sum(i)/i_len, 2),)*i_len for i, i_len in zip(L, lens)]

关于Python 在 for 循环之外获取修改后的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51250881/

相关文章:

python - 独立移动数组中的行

python - Pandas 保存时添加一个空列

python - 在列表python中相乘

java - 查找数组中的重复项并仅打印一次

javascript - 使用选择器和索引重构 jQuery

Python pandas 数据帧分割

python - 仅将日期时间列与 Pandas 中的时间进行比较

list - F# 记录和列表排序

Python:仅在列表末尾删除重复值

javascript - 如何通过值比较合并两个数组 - Google Analytics 和 MongoDB