gpt4 book ai didi

python - 在不破坏 python 结构的情况下修改 "list of lists of tuples"结构中的内容

转载 作者:太空宇宙 更新时间:2023-11-04 09:12:49 25 4
gpt4 key购买 nike

这听起来像是一个简单的问题。但是,给定一个:

a = [[(1,2)], [(3,4), (5,6)], [(7,8), (9,10), (11,12)]]

如何为元组中的第一项添加 1,以便得到后续项?

b = [[(2,2)], [(4,4), (6,6), [(8,8), (10,10), (12,12)]]

我试了一段代码如下:

b = []

for list_of_tuples in a:
for num1, num2 in list_of_tuples:
b.append((num1+1, num2))

b

但是,这会破坏原来的结构。那么,如何使用两个 for 循环获得我想要的结果?

最佳答案

使用嵌套列表理解:

>>> a = [[(1,2)], [(3,4), (5,6)], [(7,8), (9,10), (11,12)]]
>>> b = [[(x+1, y) for x, y in tuples] for tuples in a]
>>> b
[[(2, 2)], [(4, 4), (6, 6)], [(8, 8), (10, 10), (12, 12)]]

作为具有列表理解的for:

b = []
for tuples in a:
b.append([(x+1, y) for x, y in tuples])

没有任何列表理解:

b = []
for tuples in a:
tuples_b = []
for x, y in tuples:
tuples_b.append((x+1, y))
b.append(tuples_b)

关于python - 在不破坏 python 结构的情况下修改 "list of lists of tuples"结构中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13078634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com