我有点脑雾试图解决以下结构,也许有人可以帮助解决这个问题。
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
一个算法/一组循环如何生成这个表?外观的顺序并不重要。只需弹出所有四对捆绑。这些对实际上需要是个别数字,即10
是1
和0
,而不是ten
!
第一行中的一个模式是(如果只能解决这个问题会有所帮助):
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) ...
答案 0 :(得分:1)
我已经为这个问题想出了一个有效的算法:)
for row in range(4):
extra = 0
if row >= 2:
extra = 2
for column in range(6):
print(10+column, 11+column, 12+column, str(2*(row%2))+"."+str(column + extra), end = " ")
print()
把它想象成一个表,你想逐行,然后逐列工作。我使用算法中的列和行来确定数字应该是什么
如果有任何您不理解的内容,请添加评论:)
答案 1 :(得分: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)]]]
这是第二个使用&#34;传统&#34;解决方案的变体。 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
函数对其参数执行除法和模数,因此当a
和b
为整数时,divmod(a, b)
等同于a // b, a % b
。如果x
是一个两位数的整数`divmod(x,10)返回一个包含这2位数的元组。