Home > Back-end >  How do i make extra items of a list to print at the end of the rest
How do i make extra items of a list to print at the end of the rest

Time:11-08

I have this program which takes two lists as input from the user and then combines the two while alternating the items of each list. The thing is if one list is larger in length than the other i want it to print the rest of the items at the end of the result. I apologize for the bad writing of this i am new to the site

input1= input("Enter numbers of the first list with spaces in between: ")
a=input1.split()
input2=input("Enter numbers of the second list with spaces in between: ")
b = input2.split()
c = []
for x, y in zip(a, b):
  c  = [x, y]
print(c)

i tried using extend or append but it is not working

CodePudding user response:

itertools.zip_longest(*iterables, fillvalue=None)

From the itertools docs

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.

CodePudding user response:

You are looking for roundrobin:

from itertools import cycle, islice
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = cycle(islice(nexts, num_active))
            
print(list(roundrobin(a, b)))

Or, a maybe more efficient approach more_itertools.interleave_longest:

# pip install more-itertools

from more_itertools import interleave_longest

print(list(interleave_longest(a, b)))

Example

Enter numbers of the first list with spaces in between: a b c d
Enter numbers of the second list with spaces in between: 1 2 3

['a', '1', 'b', '2', 'c', '3', 'd']

CodePudding user response:

More pythonic

input1= input("Enter numbers of the first list with spaces in between: ")
a=input1.split()
input2=input("Enter numbers of the second list with spaces in between: ")
b = input2.split()

print(sum([[a.pop(0), b.pop(0)] for i in range(min(len(a), len(b)))],[]) a b)

i/p: --Even works with unequal lengths

1 2 3
4 5 6 7

output

['1', '4', '2', '5', '3', '6', '7']
  • Related