Home > other >  Python get intersection of elements from list of lists
Python get intersection of elements from list of lists

Time:08-09

I have a list of lists where each list is a string of list of int, as shown below

a = ['[11, -12, -14, 13]',
     '[8, 5, -14, 15, 13]',
     '[13, 24, -14]']

I need to find a list of common integers (intersection of lists), in this case output should be [13, -14], since they are common in all.

Is there a simple way to do this since the individual lists are str type, where I can avoid a first iteration to eval and then find set?

CodePudding user response:

  1. map() the ast.literal_eval() function over list b to safely evaluate your list of strings into a iterator of lists.
  2. Then map() the set() constructor to cast your lists to sets.
  3. Finally, use functools.reduce() with set.intersection() to find the intersection of your sets.
from functools import reduce
from ast import literal_eval

answer = reduce(set.intersection,    # 3
             map(set,                # 2
             map(literal_eval, a)))  # 1

CodePudding user response:

Not the prettiest way of solving it but it works! This will handle any number of lists in A.

a = ['[11, -12, -14, 13]',
     '[8, 5, -14, 15, 13]',
     '[13, 24, -14]']

b = []

## this block converts the strings into integers, after this b will be a, but integer lists
for ls in a:
    truncated_str = ls.replace("[", "").replace("]", "")
    my_list_of_strs = truncated_str.split(",")
    my_list_of_ints = []
    for num in my_list_of_strs:
        my_list_of_ints.append(int(num))
    
    b.append(my_list_of_ints)
    
## this functions finds commonalites
def in_all_lists(lists, value_to_check):
    
    for my_list in lists:
        if value_to_check not in my_list:
            return False
    return True

common_numbers = []


# checks to see if values are common
for lst in b:

    for value in lst:
        if value not in common_numbers and in_all_lists(b, value):
            common_numbers.append(value)
            
print(common_numbers)  # prints [-14, 13]

CodePudding user response:

import ast
from functools import reduce

lst = [] 

a = ['[11, -12, -14, 13]',
     '[8, 5, -14, 15, 13]',
     '[13, 24, -14]']

# get normal lists from the quoted ones
for s in a:
    lst.append(ast.literal_eval(s))

# get intersection of all the lists
list(reduce(set.intersection, [set(item) for item in lst ]))

[-14, 13]
  • Related