Home > Net >  Python joining an array into a single line with a new line for every two elements
Python joining an array into a single line with a new line for every two elements

Time:12-24

I have an array with 8 items like the below array (dummy data), I only want the first 6 items. I can't seem to get .join correct.

["MR_L: ", 20, "Time: ", "10:00", "Email: ", "Testing@test", "Telephone: ", 0002411212]

I want the out come to be in a string:

"MR_L: 20
Time: 10:00
Email: Testing@test"

I've tried a for loop like: for index in range (0, 5, 2) then use index -1. It is important this is all in one string as I am using a function that can only take a single string as an argument. When I use join I get a memory error.

CodePudding user response:

If the integer value(s) in your list are valid then you could do this:

mylist = ["MR_L: ", 20, "Time: ", "10:00", "Email: ", "Testing@test", "Telephone: ", 2411212]

parts = []

for i in range(0, min(6, len(mylist)), 2):
    parts.append('{}{}'.format(*mylist[i:i 2]))

print(*parts, sep='\n')

Output:

MR_L: 20
Time: 10:00
Email: Testing@test

CodePudding user response:

There are various ways to do it. One way is like this:

data = ["MR_L: ", 20, "Time: ", "10:00", "Email: ", "Testing@test", "Telephone: ", 2411212]

# STEP 1. convert all items to str type and put \n (newline) to every second items.
str_data = [str(item) if i % 2 == 0 else str(item) "\n" for i, item in enumerate(data)]
print(str_data)
# ['MR_L: ', '20\n', 'Time: ', '10:00\n', 'Email: ', 'Testing@test\n', 'Telephone: ', '2411212\n']

# STEP 2. combine the first six items 
result = "".join(str_data[:6])[:-1] # [:-1] to remove last "\n"
print(result)
"""
MR_L: 20
Time: 10:00
Email: Testing@test
"""

CodePudding user response:

Consider using the pairwise() implementation from Iterating over every two elements of a list to solve that part of your problem.

Next you can convert your pairs into strings:

[f"{k}{v}" for k, v in pairwise(allItems)]

Omit the last pair (two elements):

[f"{k}{v}" for k, v in pairwise(allItems[:-2])]

And join with newlines:

"\n".join(f"{k}{v}" for k, v in pairwise(allItems[:-2]))

CodePudding user response:

I think your data suggests a pairwise grouping:

from itertools import pairwise

data = ["MR_L: ", 20, "Time: ", "10:00", "Email: ", "Testing@test", "Telephone: ", 2411212]

# group in pairs [["MR_L: ", 20], ...]
pairs = pairwise(data) # returns an iterable

# you then join pairs (you need 3 pairs for 6 items)
"\n".join(f"{k}{v}" for k, v in list(pairs)[:3])

CodePudding user response:

You can try using generator expression and zip of the list from index 0 to length of the list -2 with 2 step and from index 1 likewise:

mylist = ["MR_L: ", 20, "Time: ", "10:00", "Email: ", "Testing@test", "Telephone: ", 2411212]

outPut = lambda lst: '\n'.join(f'{a}{b}' for a,b in zip(lst[:-2:2],lst[1::2]))

print(outPut(mylist))

# MR_L: 20
# Time: 10:00
# Email: Testing@test
  • Related