Your question seems to contains two. It is better to focus on one, but don't worry, i'll anwser both
TL; DR
Merge two list
list_A = ['abc', 'def', 'hij']
list_B = ['123','234', '345']
list_AB = []
for i in range(len(list_A)):
list_AB.append([list_A[i], list_B[i]])
# output : [['abc', '123'], ['def', '234'], ['hij', '345']]
f = open("output.txt", "w")
f.write(str(list_AB))
f.close()
Explainations
In the TL;DR I provided a simple, general solution, but i'll give here a more detailled solution for your specific case
Merge two list
We loop trought all the elements of our lists :
for i in range(len(test_names)):
combined_list = test_names[i]
combined_list.insert(0, test_numbers[i])
list_AB.append(combined_list)
Note : i
will go from 0
(included) to len(list_A)
(excluded), but if the length of list_B
is different from list_A
, we will have issues. This example should be improved if such cases are possibles.
Save to file
First opening the file link
f = open("output.txt", 'w') # 'w' for write (remove old content), we can use 'a' to append at the end of old content
Don't forget to always close your file after editing it.
f.close() # Else other program can't access the file (appear as being in use by Python)
In-between, we will write all our content to our file. We will use a forloop to iterate over all our elements inside list_AB
for element in list_AB:
f.write(str(element) + ' ;\n')
# output :
# ['123', 'timothy', 'tim'] ;
# ['234', 'clara'] ;
# ['345', 'jerry', 'jer', 'j-dog'] ;
That is not exactly what we want. List are displayed as ["element1", "element2", ...]
, but we want a prettier output. We can use .join() :
e.g. 'something'.join(list_AB)
That will concat all element of the list, each separeted by a string (here the string "something")
for element in list_AB:
f.write(' ; '.join(element) + ' ;\n')
# output :
# 123 ; timothy ; tim;
# 234 ; clara;
# 345 ; jerry ; jer ; j-dog;
Perfect :)
(don't forget to close your file)