Reputation: 23
I have this problem that I could not find a solution for quite a while. My guess is that the best approach is via re, but I am open to any suggestions.
I have the text below in a list which I wrote to a text file to be imported by a different program for some calculation.
The problem is that I have to include matched line (i.e []s=0) with similar []s=0 like this:[]s=0 -> p01:(s'=1) + p02:(s'=2). So, the first two lines must be combined by a + operator and so the following third and fourth line and so forth.
module main
[]s=0 -> p01:(s'=1);
[]s=0 -> p02:(s'=2);
[]s=1 -> p10:(s'=0);
[]s=1 -> p12:(s'=2);
[]s=2 -> p20:(s'=0);
[]s=2 -> p23:(s'=3);
[]s=3 -> p34:(s'=4);
[]s=4 -> p40:(s'=0);
[]s=4 -> p45:(s'=5);
[]s=4 -> p46:(s'=6);
[]s=5 -> p57:(s'=7);
[]s=6 -> p67:(s'=7);
[]s=7 -> p70:(s'=0);
endmodule
Upvotes: 0
Views: 42
Reputation: 186
Assuming you have the data as strings?
data = ["[]s=0 -> p01:(s'=1);",
"[]s=0 -> p02:(s'=2);",
"[]s=1 -> p10:(s'=0);",
"[]s=1 -> p12:(s'=2);",
"[]s=2 -> p20:(s'=0);",
"[]s=2 -> p23:(s'=3);",
"[]s=3 -> p34:(s'=4);",
"[]s=4 -> p40:(s'=0);",
"[]s=4 -> p45:(s'=5);",
"[]s=4 -> p46:(s'=6);",
"[]s=5 -> p57:(s'=7);",
"[]s=6 -> p67:(s'=7);",
"[]s=7 -> p70:(s'=0);"]
dict_ = {}
for item in data:
split = (item.split("=")[1].split(" ")[0])
if not split in dict_:
dict_[split] = item
else:
dict_[split] = dict_[split] + " + " + item
for key, value in dict_.items() :
print (key, value)
Upvotes: 1