I have this list:
ls = [[0, 'C', [1, 2, 3, 4], 'E', []],
[1, 'C', [0, 5, 6, 7], 'E', []],
[2, 'H', [0], '-', []],
[3, 'H', [0], '-', []],
[4, 'H', [0], '-', []],
[5, 'H', [1], '-', []],
[6, 'O', [1], 'X', []],
[7, 'H', [1], '-', []]]
This represents a molecule. The first column is just a number, the second column is an atom in the molecule, the third column tells which atoms this atom is bound to. For example, atom 0 is bound to atoms 1, 2, 3 and 4. I want to find out how far away each atom is from the oxygen, and this is info is stored to the last column. So the output should be:
[[0, 'C', [1, 2, 3, 4], 'E', 2],
[1, 'C', [0, 5, 6, 7], 'E', 1],
[2, 'H', [0], '-', 3],
[3, 'H', [0], '-', 3],
[4, 'H', [0], '-', 3],
[5, 'H', [1], '-', 2],
[6, 'O', [1], 'X', 0],
[7, 'H', [1], '-', 2]]
I tried this loop and it works just fine:
def dists(data):
new_data = data
# Loop to find the distances from the X-atom:
for sl2 in new_data:
if sl2[3] == "X":
sl2[4] = 0
next1 = sl2[2]
for number1, row1 in enumerate(new_data):
for a1 in next1:
if new_data[number1][0] == a1:
if type(new_data[a1][4]) == list:
new_data[a1][4] = 1
next2 = new_data[a1][2]
for number2, row2 in enumerate(new_data):
for a2 in next2:
if new_data[number2][0] == a2:
if type(new_data[a2][4]) == list:
new_data[a2][4] = 2
next3 = new_data[a2][2]
for number3, row3 in enumerate(new_data):
for a3 in next3:
if new_data[number3][0] == a3:
if type(new_data[a3][4]) == list:
new_data[a3][4] = 3
next4 = new_data[a3][2]
#etc...
return new_data
ls2 = dists(ls)
But now I have to make many nested for loops. How can I turn these nested loops into a single loop?
EDIT for @deadshot
The value of the fifth column comes from these:
sl2[4] = 0
new_data[a1][4] = 1
new_data[a2][4] = 2
new_data[a3][4] = 3
etc...
In the fourth column the "X" just helps me to find the starting point which is the oxygen atom.