简体   繁体   中英

How to group a list of tuples based on the strings they contain?

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

Coming from a Ruby background, I often felt the need to use something like Enumerable#slice_before in Python. It basically splits any iterable into chunks. The slice is done before every element for which the predicate is true.

Based on the Rubinius implementation , I ported the code to Python.

def slice_before(iterable, predicate):
    chunk = None
    for elem in iter(iterable):
        if predicate(elem):
            if chunk:
                yield chunk
            chunk = [elem]
        else:
            if not chunk:
                chunk = []
            chunk.append(elem)
    if chunk:
        yield chunk

Here are a few examples:

>>> list(slice_before(range(12), lambda i: i % 3 == 0))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
>>> list(slice_before('LetsTestSliceBefore', str.isupper))
[['L', 'e', 't', 's'], ['T', 'e', 's', 't'], ['S', 'l', 'i', 'c', 'e'], ['B', 'e', 'f', 'o', 'r', 'e']]

You just need to initialize your data. Note that code_list could be a set for faster lookup:

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'}

The required code for your problem becomes a one-liner with slice_before :

print(list(slice_before(original_list, lambda x_y: x_y[0] in code_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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM