Reputation: 29
If I have output that looks like this
[[121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111],
[82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 110],
[83, 50, 49, 48, 47, 46, 45, 44, 43, 72, 109],
[84, 51, 26, 25, 24, 23, 22, 21, 42, 71, 108],
[85, 52, 27, 10, 9, 8, 7, 20, 41, 70, 107],
[86, 53, 28, 11, 2, 1, 6, 19, 40, 69, 106],
[87, 54, 29, 12, 3, 4, 5, 18, 39, 68, 105],
[88, 55, 30, 13, 14, 15, 16, 17, 38, 67, 104],
[89, 56, 31, 32, 33, 34, 35, 36, 37, 66, 103],
[90, 57, 58, 59, 60, 61, 62, 63, 64, 65, 102],
[91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101]]
how do I get it to where I can find and print a certain number and the numbers surrounding it? This is my code.
dim = 11
dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
x, y, c = 0, -1, dim**2
m = [[0 for i in range(dim)] for j in range(dim)]
for i in range(dim + dim - 1):
for j in range((dim + dim - i) // 2):
x += dx[i % 4]
y += dy[i % 4]
m[x][y] = c
c -= 1
print(m)
b = c.index(num)
print(b)
a =('\n'.join([' '.join([str(v) for v in r])for r in m]))
print(a)
Upvotes: 0
Views: 561
Reputation: 881715
Assuming that list-of-lists is called lol
:-):
def neighbors(lol, anum):
for i, row in enumerate(lol[1:-1]):
try: where = row.index(anum)
except ValueError: continue
if where==0 or where==len(row)-1: continue
for j in range(i, i+3):
print(lol[j][where-1], lol[j][where], lol[j][where+1])
print()
This embodies several assumptions, such as: (A) you don't care for hits on the first or last row or column since they don't have all the neighbors you want to print, and also (B) you don't care about multiple "hits" in a single row but (C) do care about "hits" in multiple rows.
Of course all such assumptions can be changed but that requires you to be much more precise in your specs than you've been so far:-).
The print
format assumes either Python 3 or a from __future__ import print_function
if you're stuck with Python 2.
Upvotes: 1
Reputation: 107297
First in this case as c
is a int value hasn't attribute index
. so the following command will raise an AttributeError
.
b = c.index(num)
and for get the desire result all that you need here is reversing the r
list in following command , and for print you can use format
:
a =('\n'.join([' '.join(["{:3}".format(v) for v in r[::-1]])for r in m]))
so the result will be :
111 112 113 114 115 116 117 118 119 120 121
110 73 74 75 76 77 78 79 80 81 82
109 72 43 44 45 46 47 48 49 50 83
108 71 42 21 22 23 24 25 26 51 84
107 70 41 20 7 8 9 10 27 52 85
106 69 40 19 6 1 2 11 28 53 86
105 68 39 18 5 4 3 12 29 54 87
104 67 38 17 16 15 14 13 30 55 88
103 66 37 36 35 34 33 32 31 56 89
102 65 64 63 62 61 60 59 58 57 90
101 100 99 98 97 96 95 94 93 92 91
Upvotes: 0