Home > Software design >  How to create a set of values from multiple list in Python
How to create a set of values from multiple list in Python

Time:10-05

I have below data in config.json:

{
  "data1": [7, 8],
  "data2": [2015, 2016],
  "data3": [5, 10],
}

It has 3 list with length as 2 but it can have multiple list with n length. I have to read this data and then create a list of list which should have all the values just like set. So output should look like below:

[
    [7, 2015, 5],
    [7, 2015, 10],
    [7, 2016, 5],
    [7, 2016, 10],
    [8, 2015, 5],
    [8, 2015, 10],
    [8, 2016, 5],
    [8, 2016, 10]
]


json_data = open("config.json")
config = json.load(json_data)
json_data.close()

data_list = []
for be in config["data1"]:
    for eof in config["data2"]:
        for bd in config["data3"]:
            data_list.append(bd)

But I am unable to understand how do I modify the data to have output like above. Can anyone please give some suggestion. Please help. Thanks

CodePudding user response:

You can use itertools.product:

list(it.product(*data.values()))

CodePudding user response:

Use itertools.product which gives the Cartesian product of a series of iterables:

from itertools import product
data = {'data1': [7, 8], 'data2': [2015, 2016], 'data3': [5, 10]}
cprod = product(*data.values())
for cp in cprod:
    print(cprod)
(7, 2015, 5)
(7, 2015, 10)
(7, 2016, 5)
(7, 2016, 10)
(8, 2015, 5)
(8, 2015, 10)
(8, 2016, 5)
(8, 2016, 10)


CodePudding user response:

you have done all the work just add

    data_list = []
    for be in config["data1"]:
        for eof in config["data2"]:
            for bd in config["data3"]:
                data_list.append([be,eof,bd])

CodePudding user response:

Here's some information about a_guest's answer, as you seems to have some trouble understand it.

json_data = open("config.json")
config = json.load(json_data)
json_data.close()

cproduct = list(itertools.product(*config.values()))

product function will give you the cartesian product, that's exactly what you need : all possible combination of elements from different set. We basically use it as product(set_1, set_2, ..., set_n).

Here, set_1 should be the list stored with the "data1" key, set_2 with "data2" and so on. So you could basically write it.product(config['data1'], config['data2'], config['data3']).

But how can we deals with new keys in the json without changing our code ?

To achieve this, guest_a relies on two things :

  • config.values() which return a list of every values, so in your case a list containing all the list defined in your json. This way, you'll get the new list if you add a new "data4" key into your json file.

  • Unpacking * operator, which allow us to use any iterable as a list of arguments.

So basically, it.product(*config.values()) is equivalent to it.product(config["data1"], ..., config["data_n"]), but is much more flexible.

  • Related