Reputation: 39
I have the following code in place
Trans_Func = [['s1', '@', 's2'], ['s1', '@', 's4'], ['s2', '0', 's2'], ['s2', '1', 's3'], ['s3', '0', 's3'], ['s3', '1', 's3'], ['s3', '2', 's3'], ['s4', '1', 's4'], ['s4', '2', 's4'], ['s4', '2', 's5']]
new_rules = []
for i, j in Trans_Func:
if i[0] == j[0] and i[1] == j[1]:
#operation to append the new rule
print(new_rules)
I am trying to create a new list that contains elements from Trans_Func only when the first strings are equivalent, the second strings are equivalent, but the third strings are different. My expected output for new_rules is:
new_rules = [['s1', '@', 's1, s4'], ['s4', '2', 's4, s5']]
I just do not know how to loop through Trans_Func in an attempt to inspect multiple elements at the same time.
Upvotes: 0
Views: 59
Reputation: 42143
You can use a dictionary to manage matching pairs as keys and accumulate the 3rd strings in a list as the values. Then run through the dictionary to isolate pairs that have more than one associated 3rd string:
d = dict()
for s1,s2,s3 in Trans_Func: d.setdefault((s1,s2),[]).append(s3)
new_rules = [ [s1,s2,", ".join(ss)] for (s1,s2),ss in d.items() if len(ss)>1 ]
print(new_rules)
[['s1', '@', 's2, s4'], ['s4', '2', 's4, s5']]
Upvotes: 1
Reputation: 146
Here you go
for i in range(len(Trans_Func)):
IF i<len(Trans_Func)-1:
if Trans_Func[i][1]==Trans_Func[i+1][1] and Trans_Func[i][2]==Trans_Func[i+1][2]:
#operation to append the new rule
Upvotes: 1
Reputation: 92854
Give your variables a proper names (lowercase and meaningful), say trans_list
(for ex.).
With effective generator expression and zip
function:
trans_list = [['s1', '@', 's2'], ['s1', '@', 's4'], ['s2', '0', 's2'], ['s2', '1', 's3'], ['s3', '0', 's3'],
['s3', '1', 's3'], ['s3', '2', 's3'], ['s4', '1', 's4'], ['s4', '2', 's4'], ['s4', '2', 's5']]
new_rules = list([lst_1[0], lst_1[1], lst_1[2] + ', ' + lst_2[2]]
for lst_1, lst_2 in zip(trans_list[:-1], trans_list[1:])
if lst_1[:2] == lst_2[:2] and lst_1[2] != lst_2[2])
print(new_rules)
The output:
[['s1', '@', 's2, s4'], ['s4', '2', 's4, s5']]
Upvotes: 0