如何简化Python中切片多组坐标并转换为元组的代码?
简化方案
你可以用生成器表达式直接生成目标元组,彻底避免重复索引的冗余代码,还能灵活适配任意长度的coordinates列表:
coordinates = [ (9, 2, 17), (4, 14, 11), (8, 10, 6), (2, 7, 0) ] newCnds = tuple(coord[:2] for coord in coordinates)
补充说明:
- 原代码里
cdns = coordinates[0][:2], coordinates[1][:2], ...本身已经是元组(Python中逗号分隔的序列默认是元组),所以newCnds = tuple(cdns)属于多余操作,直接用cdns就是你要的结果。 - 用循环式的生成器/列表推导,不仅代码更简洁,还能自动处理
coordinates长度变化的情况,不用手动逐个写索引。
如果偏好列表推导的写法,也可以这样:
newCnds = tuple([coord[:2] for coord in coordinates])
不过生成器表达式更节省内存,尤其是处理大量数据时。
内容的提问来源于stack exchange,提问作者ghosty
相关产品推荐
相关产品推荐

