python - Python将修改后的列表放在for循环之外
问题描述
我一直在研究一种制作元组列表并找到每个元组的平均值的方法。
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)]
解决方案
您可以使用列表推导。map
下面是一个示例,它避免通过和zip
迭代器计算每个元组的长度两次。
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)]
推荐阅读
- apache-spark - 使用不使用 UDF 的数字范围创建 Df 列
- sublimetext3 - 在 sublime3 中无法连接到 HERMES
- sql-server - 验证是否在查询中的任何地方都进行了特定的连接
- sql - 过去 12 个月的累计金额 - 缺少日期?
- javascript - OAuth 2.0 in Node js Access Token Error The content-type is not JSON compatible
- python - 从 CLI 运行时出现 Python“ModuleNotFound”错误,但在“pip install -e”之后从 Pycharm 运行时不会出现错误。”(使用 Anaconda)
- python - Python 日志记录:即使处理程序级别为 INFO,调试消息也会记录到 stderr
- sql - 在 Mysql Workbench 中保存和导出 EER 图布局
- python-3.x - python覆盖父母行为,同时保留父母方法和名称
- excel - 如何在不导入新文件的情况下异步发出请求