Reputation: 37
I'm creating a Python dictionary at run time as below,
valueDict = {(0, 0): 'P0', (20, 0): 'P1', (20, 11.36): 'P2', (0, 11.36): 'P3'}
I have two arrays;
values = [[0, 0, 20, 0, 15, 5.5, 5, 5.5]
[20, 0, 20, 11.36, 15, 5.5]
[20, 11.6, 0, 11.36, 5, 5.5, 15, 5.5]
[0, 11.36, 0, 0, 5, 5.5]]
data = [5, 5.5, 15, 5.5]
data[0] -> D0
data[1] -> D1
I want to replace values of values
array with dict values and data array values.
So the output should be;
[
["P0", "P1", "D1", "D0"],
["P1", "P2", "D1"],
["P2", "P3", "D0", "D1"],
["P3", "P0", "D0"]
]
What I have tried is,
for x in range(0,len(values), 1):
y = 0
oneD = values[x]
for i, j in valueDict.iteritems():
print("y ", y)
print("left : ",(oneD[y], oneD[y+1])," right : ",i)
if ((oneD[y], oneD[y+1]) == i ):
oneD[y] = oneD[y].replace(j)
oneD[y+1] = oneD[y+1].replace(j)
elif((oneD[y], oneD[y+1]) == data[0]):
oneD[y] = oneD[y].replace("D0")
oneD[y+1] = oneD[y+1].replace("D0")
elif((oneD[y], oneD[y+1]) == data[1]):
oneD[y] = oneD[y].replace("D1")
oneD[y+1] = oneD[y+1].replace("D1")
else:
y += 2
continue
y += 2
This code is not working properly. How can I do this?
Upvotes: 2
Views: 251
Reputation: 49784
value_dict = {(0, 0): 'P0', (20, 0): 'P1', (20, 11.36): 'P2',
(0, 11.36): 'P3'}
values = [
[0, 0, 20, 0, 15, 5.5, 5, 5.5],
[20, 0, 20, 11.36, 15, 5.5],
[20, 11.36, 0, 11.36, 5, 5.5, 15, 5.5],
[0, 11.36, 0, 0, 5, 5.5]
]
data = [5, 5.5, 15, 5.5]
# add data to value_dict
iterator = iter(data)
for i, j in enumerate(iterator):
value_dict[j, next(iterator)] = 'D{}'.format(i)
# Translate the data
result = []
for v in values:
line = []
iterator = iter(v)
for i in iterator:
line.append(value_dict[(i, next(iterator))])
result.append(line)
print(value_dict)
print(result)
{
(0, 0): 'P0',
(20, 0): 'P1',
(20, 11.36): 'P2',
(0, 11.36): 'P3',
(5, 5.5): 'D0',
(15, 5.5): 'D1'
}
[
['P0', 'P1', 'D1', 'D0'],
['P1', 'P2', 'D1'],
['P2', 'P3', 'D0', 'D1'],
['P3', 'P0', 'D0']
]
Upvotes: 2
Reputation: 7331
First add (5, 5.5): 'D0', (15, 5.5): 'D1'
to valueDict
:
valueDict = {(0, 0): 'P0', (20, 0): 'P1', (20, 11.36): 'P2', (0, 11.36): 'P3', (5, 5.5): 'D0', (15, 5.5): 'D1'}
And change the 11.6
for 11.36
in values:
values = [[0, 0, 20, 0, 15, 5.5, 5, 5.5],
[20, 0, 20, 11.36, 15, 5.5],
[20, 11.36, 0, 11.36, 5, 5.5, 15, 5.5],
[0, 11.36, 0, 0, 5, 5.5]]
First we go through it and we turn it into tuples:
tuples_values = []
for v in values:
tuples_values.append([(v[i], v[i+1]) for i in range(0, len(v), 2)])
Then we go through it and replace it with the values of the dict:
out = []
for v in tuples_values:
out.append([valueDict[tuple_value] for tuple_value in v])
out:
[['P0', 'P1', 'D1', 'D0'],
['P1', 'P2', 'D1'],
['P2', 'P3', 'D0', 'D1'],
['P3', 'P0', 'D0']]
Upvotes: 2