Skip to content
Advertisement

How to append several phrases of a string to different lists in a loop

it is actually really difficult to write a suitable title for this question, so please correct if you find something more percise.

My problem is basically, that I have a txt file with a pattern which i want to sort.

Consider the following string

url1
cust1
number1
url2
cust2
number2
url3
cust3
number3
url4
cust4
number4

So all the lines are seperated and the pattern is the same. What i want to do now is to make 3 lists one for url one for cust and the last for number.

I have basically no idea how to do that as there is no pattern which I could search for with regex. So my idea was to do something like this:

for i in range(1, 3, len(txt)):
   l1.append(i)

And this i would do for all the 3 lists. Is there some other easier and more advanced solution?

Advertisement

Answer

with open('path/to/input') as infile:
    lines = (line.strip() for line in infile)

    urls, custs, nums = zip(*zip(lines, lines, lines))

Output:

In [241]: urls
Out[241]: ('url1', 'url2', 'url3', 'url4')

In [242]: custs
Out[242]: ('cust1', 'cust2', 'cust3', 'cust4')

In [243]: nums
Out[243]: ('number1', 'number2', 'number3', 'number4')
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement