I have following lists from user input
name = [ "name0", "name1", "name2" ]
year = [ "year0", "year1", "year2" ]
salary = [ "salary0", "salary1", "salary2"]
How do create a single outer list like this:
my_list = [["name0", "year0", "salary0"]
["name1", "year1", "salary1"]
["name2", "year2", "salary2"]]
I tried the following but didn't work:
for a in range(len(name)):
my_list = [name[a], year[a], salary[a]]
CodePudding user response:
You can use zip
to iterate all three lists together:
out = [list(data) for data in zip(name, year, salary)]
For your current code to work, you could define an empty list first, then append a sublist in loop:
my_list = []
for a in range(len(name)):
my_list.append([name[a], year[a], salary[a]])
Output:
[['name0', 'year0', 'salary0'],
['name1', 'year1', 'salary1'],
['name2', 'year2', 'salary2']]
CodePudding user response:
If you don't mind using numpy array, you can just transpose the three lists and you will get you desired output.
np.array([name,year,salary]).T
Out[31]:
array([['name0', 'year0', 'salary0'],
['name1', 'year1', 'salary1'],
['name2', 'year2', 'salary2']], dtype='<U7')