Reputation: 43
This is my current code and the output is
['50003252714', 'Malle Kask',
'40003252714', 'Endel Kask',
'30003252714', 'Peeter Kask',
'60003252714', 'JĆ¼ri MƤnd',
'70003252714', 'Laura MƤnd',
'80003252714', 'Kerli MƤnd',
'10003252714', 'Elvo Pikk',
'20003252714', 'Signal Pikk']
What I want to do is make a new list inside the original list with 2 following elements. An example of what I want as an end result is
[["50003252714","Malle Kask"],
["40003252714","Endel Kask"],
[...]]
I tried using for and while loops inside each other but it got really messy and I didn't get my desired result.
nimedFail = open("nimed.txt")
lapsedFail = open("lapsed.txt")
def seosta_lapsed_ja_vanemad(lapsed,nimed):
nimed = []
lapsed = []
eraldatud_nimed_töötlemata = []
eraldatud_nimed = []
eraldatud_nimed_listides = []
for rida in nimedFail:
nimed.append(rida.strip())
for rida in lapsedFail:
lapsed.append(rida.strip())
for ele in nimed:
eraldatud_nimed_töötlemata.append(ele.split(" "))
for ele in eraldatud_nimed_töötlemata:
x = " ".join(ele[1:3])
eraldatud_nimed.append(ele[0])
eraldatud_nimed.append(x)
return eraldatud_nimed
print(seosta_lapsed_ja_vanemad("nimed.txt","lapsed.txt"))
Upvotes: 2
Views: 89
Reputation: 533
I really don't understand the variable names but I'll try to code it.
def seosta_lapsed_ja_vanemad(lapsed,nimed):
with open(lapsed, 'r') as lapsed_file_handler:
lapsed_content = lapsed_file_handler.readlines()
with open(nimed, 'r') as nimed_file_handler:
nimed_content = nimed_file_handler.readlines()
Assuming both files are equal in line numbers, you may just loop through them:
return [[lapsed_content[i], nimed_content[i]] for i in range(0, len(lapsed_content))]
I suggest you use tuple or dictionary instead of nested list.
Upvotes: 0
Reputation: 154
There is my way of doing this:
list = ['50003252714', 'Malle Kask',
'40003252714', 'Endel Kask',
'30003252714', 'Peeter Kask',
'60003252714', 'JĆ¼ri MƤnd',
'70003252714', 'Laura MƤnd',
'80003252714', 'Kerli MƤnd',
'10003252714', 'Elvo Pikk',
'20003252714', 'Signar Pikk']
Convert the list using iter() and then within the loop use next() iterator:
it = iter(a)
final = []
for a in it:
list_of_two = [a, next(it)]
final.append(list_of_two)
print(final)
Output:
[['50003252714', 'Malle Kask'], ['40003252714', 'Endel Kask'], ['30003252714', 'Peeter Kask'], ['60003252714', 'JĆ¼ri MƤnd'], ['70003252714', 'Laura MƤnd'], ['80003252714', 'Kerli MƤnd'], ['10003252714', 'Elvo Pikk'], ['20003252714', 'Signar Pikk']]
Upvotes: 1
Reputation: 25604
you can likely create the combined list / list of lists already when reading the files, something along the lines of
with open("nimed.txt", 'r') as nimedFail, open("lapsed.txt", 'r') as lapsedFail:
l_out = [[a.strip(), b.strip()] for a, b in zip(nimedFail, lapsedFail) if a.strip() and b.strip()]
Upvotes: 1