I have a sorted list of two-string tuples. I also have another list of 4 character strings that are in some of those tuples. I would like to group from one of these 4 character strings to the next in the list. It is a bit hard to explain so I will demonstrate.
original_list = [('1321', 01), ('MessageXZY', 02), ('DescriptionSKS', 03), ('S7_6', 04), ('S7_3', 05), ('0A3B', 06), ('MessageZYA', 07),
('DescriptionKAM', 08), ('9K44', 09), ('MessageYAL', 10),
('DescriptionAUS', 11), ('S7_2', 12)]
I have the terms 1321, OA3B and 9K44 saved in another list. I would like to group everything between (and including) these terms into a tuple, like so:
grouped_list = [(('1321', 01), ('MessageXZY', 02), ('DescriptionSKS', 03), ('S7_6', 04), ('S7_3', 05)), (('0A3B', 06), ('MessageZYA', 07),
('DescriptionKAM', 08)), (('9K44', 09), ('MessageYAL', 10),
('DescriptionAUS', 11), ('S7_2', 12))]
If the list that contains my 4 character terms is called code and the list containing the tuples is called original_list, what code would I need to achieve this?
Edit: This is where I have gotten up to:
grouped_list = []
for tuple in original_list:
for string in tuple:
if string in code:
grouped_list = list(zip ##zip that tuple and all consecutive tuples until the next item in code
I am assuming that you have list of codes with which you want to split on. According to that see if this code works for you.
original_list = [('1321', '01'), ('MessageXZY', '02'), ('DescriptionSKS', '03'), ('S7_6', '04'), ('S7_3', '05'), ('0A3B', '06'), ('MessageZYA', '07'), ('DescriptionKAM', '08'), ('9K44', '09'), ('MessageYAL', '10'),
('DescriptionAUS', '11'), ('S7_2', '12')]
code_list = ['1321', '0A3B','9K44']
grouped_tuples = []
for entry in original_list:
if entry[0] in code_list:
new_tuple = []
new_tuple.append(entry)
for i in range(original_list.index(entry)+1, len(original_list)):
if(original_list[i][0] not in code_list):
new_tuple.append(original_list[i])
else:
break
grouped_tuples.append(tuple(new_tuple))
print grouped_tuples
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments