I have a list, where I need to traverse through the entire list and I need to delete the list item once the list is updated. How to do it?
In this below program, once I am traversing the list with two for loops
. Once the port number matched
then I have to append the list with new values and I want to delete that particular index
once the value is been updated. How to do it
abc = [["in", {"Att":[2], "port":1, "val":[2]}],
["in", {"Att":[1], "port":2, "val":[1]}],
["in", {"Att":[3], "port":1, "val":[3]}],
["in", {"Att":[4], "port":2, "val":[4]}],
["in", {"Att":[5], "port":1, "val":[5]}]]
for i in xrange(len(abc)):
for j in xrange((i+1), len(abc)):
if abc[i][1]["port"] == abc[j][1]["port"]:
abc[i][1]["Att"].append(abc[j][1]["Att"][0])
abc[i][1]["val"].append(abc[j][1]["val"][0])
#del abc[j]
print abc
I expected output should be
#[["in", {"Att":[2,3,5], "port":1, "val":[2,3,5]}],
# ["in", {"Att":[1,4], "port":1, "val":[1,4]}]]
But the actual output is
#[['in', {'Att': [2, 3, 5], 'port': 1, 'val': [2, 3, 5]}],
#['in', {'Att': [1, 4], 'port': 2, 'val': [1, 4]}],
#['in', {'Att': [3, 5], 'port': 1, 'val': [3, 5]}],
#['in', {'Att': [4], 'port': 2, 'val': [4]}],
#['in', {'Att': [5], 'port': 1, 'val': [5]}]]
Update:
I have taken another list but here I am getting duplicates in the list
abc = [["in", {"Att":[2], "port":1, "val":[2]}],
["in", {"Att":[1], "port":2, "val":[1]}],
["in", {"Att":[3], "port":1, "val":[3]}],
["in", {"Att":[4], "port":2, "val":[4]}],
["in", {"Att":[5], "port":1, "val":[5]}],
["in", {"Att":[6], "port":2, "val":[6]}]]
index = []
temp_list = []
for i in xrange(len(abc)):
for j in xrange((i+1), len(abc)):
if abc[i][1]["port"] == abc[j][1]["port"] and j not in index:
index.append(j)
abc[i][1]["Att"].append(abc[j][1]["Att"][0])
abc[i][1]["val"].append(abc[j][1]["val"][0])
temp_list.append(abc[i])
#del temp_list[len(temp_list)]
print temp_list
Output is coming as
[['in', {'Att': [2, 3, 5], 'port': 1, 'val': [2, 3, 5]}],
['in', {'Att': [2, 3, 5], 'port': 1, 'val': [2, 3, 5]}],
['in', {'Att': [1, 4, 6], 'port': 2, 'val': [1, 4, 6]}],
['in', {'Att': [1, 4, 6], 'port': 2, 'val': [1, 4, 6]}]]