Let's say for example, I have the following two lists:
name = ["Joe Harris", "Susie Carmike"]
method = ["Lab"]
How can I map these two lists to where the output would be below? Or is there a better way other than lists in Python to map elements of different size to get such an output?
name method
Joe Harris Lab
Susie Carmike Lab
CodePudding user response:
You can use itertools.product
like below:
import itertools
name = ["Joe Harris", "Susie Carmike"]
method = ["Lab"]
somelists = [name] [method]
for element in itertools.product(*somelists):
print(element)
Output:
('Joe Harris', 'Lab')
('Susie Carmike', 'Lab')
Or:
>>> list(itertools.product(*somelists))
[('Joe Harris', 'Lab'), ('Susie Carmike', 'Lab')]
For creating DataFrame try this:
data = list(itertools.product(*somelists))
df = pd.DataFrame(data, columns=['name', 'method'])
print(df)
Output:
name method
0 Joe Harris Lab
1 Susie Carmike Lab
You can use this method for multi list
like below:
import itertools
name = ["Joe Harris", "Susie Carmike", "Joe Harris2"]
method = ["Lab", 'Lab2']
approach = ['app1', 'app2']
somelists = [name] [method] [approach]
list(itertools.product(*somelists))
Output:
[('Joe Harris', 'Lab', 'app1'),
('Joe Harris', 'Lab', 'app2'),
('Joe Harris', 'Lab2', 'app1'),
('Joe Harris', 'Lab2', 'app2'),
('Susie Carmike', 'Lab', 'app1'),
('Susie Carmike', 'Lab', 'app2'),
('Susie Carmike', 'Lab2', 'app1'),
('Susie Carmike', 'Lab2', 'app2'),
('Joe Harris2', 'Lab', 'app1'),
('Joe Harris2', 'Lab', 'app2'),
('Joe Harris2', 'Lab2', 'app1'),
('Joe Harris2', 'Lab2', 'app2')]
CodePudding user response:
Try itertools.cycle
:
>>> from itertools import cycle
>>> list(zip(name, cycle(method)))
[('Joe Harris', 'Lab'), ('Susie Carmike', 'Lab')]
>>>