gpt4 book ai didi

python - 生成一个循环以达到特定结果

转载 作者:行者123 更新时间:2023-12-01 03:34:22 26 4
gpt4 key购买 nike

我有点脑雾试图解决以下结构,也许有人可以帮助解决这个问题。

 10 11 12 00   11 12 13 01  12 13 14 02  13 14 15 03   14 15 16 04   15 16 17 05

10 11 12 20 11 12 13 21 12 13 14 22 13 14 15 23 14 15 16 24 15 16 17 25

10 11 12 02 11 12 13 03 12 13 14 04 13 14 15 05 14 15 16 06 15 16 17 07

10 11 12 22 11 12 13 23 12 13 14 24 13 14 15 25 14 15 16 26 15 16 17 27

生成此表的算法/循环集会是什么样子?出现的顺序并不重要。应该会弹出所有四对的 bundle 。这些对实际上需要是单独的数字,即 1010,而不是 10 !

编辑:数字中肯定存在某种模式。但我没有设法创建一个适当的循环来“捕获”该模式。

第一行中的一个模式是(如果可以解决这个问题就已经有帮助了):

 x = 1
i = 0
xi x(i+1) x(i+2) (x-1)i x(i+1) x(i+2) x(i+3) (x-1)(i+1) ...

最佳答案

此代码生成所需的数据作为 3D 字符串列表。

a = (0, 0), (2, 0), (0, 2), (2, 2)
b = 10, 11, 12
result = [
[
[str(i + j) for j in b] + [str(u) + str(v+i)] for i in range(6)
] for u, v in a
]

# Display the resulting list in a relatively compact way
for row in result:
print([' '.join(u) for u in row])

输出

['10 11 12 00', '11 12 13 01', '12 13 14 02', '13 14 15 03', '14 15 16 04', '15 16 17 05']
['10 11 12 20', '11 12 13 21', '12 13 14 22', '13 14 15 23', '14 15 16 24', '15 16 17 25']
['10 11 12 02', '11 12 13 03', '12 13 14 04', '13 14 15 05', '14 15 16 06', '15 16 17 07']
['10 11 12 22', '11 12 13 23', '12 13 14 24', '13 14 15 25', '14 15 16 26', '15 16 17 27']
<小时/>

如果这些对实际上应该是整数对,我们需要一个稍微不同的策略:

from pprint import pprint

a = (0, 0), (2, 0), (0, 2), (2, 2)
b = 10, 11, 12
result = [
[
[divmod(i + j, 10) for j in b] + [(u, v+i)] for i in range(6)
] for u, v in a
]

pprint(result)

输出

[[[(1, 0), (1, 1), (1, 2), (0, 0)],
[(1, 1), (1, 2), (1, 3), (0, 1)],
[(1, 2), (1, 3), (1, 4), (0, 2)],
[(1, 3), (1, 4), (1, 5), (0, 3)],
[(1, 4), (1, 5), (1, 6), (0, 4)],
[(1, 5), (1, 6), (1, 7), (0, 5)]],
[[(1, 0), (1, 1), (1, 2), (2, 0)],
[(1, 1), (1, 2), (1, 3), (2, 1)],
[(1, 2), (1, 3), (1, 4), (2, 2)],
[(1, 3), (1, 4), (1, 5), (2, 3)],
[(1, 4), (1, 5), (1, 6), (2, 4)],
[(1, 5), (1, 6), (1, 7), (2, 5)]],
[[(1, 0), (1, 1), (1, 2), (0, 2)],
[(1, 1), (1, 2), (1, 3), (0, 3)],
[(1, 2), (1, 3), (1, 4), (0, 4)],
[(1, 3), (1, 4), (1, 5), (0, 5)],
[(1, 4), (1, 5), (1, 6), (0, 6)],
[(1, 5), (1, 6), (1, 7), (0, 7)]],
[[(1, 0), (1, 1), (1, 2), (2, 2)],
[(1, 1), (1, 2), (1, 3), (2, 3)],
[(1, 2), (1, 3), (1, 4), (2, 4)],
[(1, 3), (1, 4), (1, 5), (2, 5)],
[(1, 4), (1, 5), (1, 6), (2, 6)],
[(1, 5), (1, 6), (1, 7), (2, 7)]]]
<小时/>

这是第二个解决方案的变体,它使用“传统”for 循环而不是嵌套列表推导式。希望它更容易阅读。 :)

a = (0, 0), (2, 0), (0, 2), (2, 2)
b = 10, 11, 12
result = []
for u, v in a:
row = []
for i in range(6):
row.append([divmod(i + j, 10) for j in b] + [(u, v+i)])
result.append(row)

内置divmod函数对其参数执行除法和模运算,因此当 ab 为整数时,divmod(a, b) 相当于 a//b, a % b.如果 x 是两位数整数,则 divmod(x, 10) 返回包含这 2 位数字的元组。

关于python - 生成一个循环以达到特定结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40528981/

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