Macklemore
Macklemore

Reputation: 53

Creating links between two elements in a list

Pardon me if the question is easy but i am stuck at this point. I have a code which looks like this:

list=[1,2,3,4]

for Source, Destination in zip(list, list[1:]):
     print ("Source: "),Source
     print ("Destination: "),Destination

Even though it is giving me an output of the source and destination at every zipped array. So, how can i get an output such as:

Source = 1
Intermediate destination = 2

Intermediate Source = 2
Intermediate destination = 3

Intermediate Source = 3
Final Destination = 4

?

The code should work with a different sized list as well. And unfortunately no NumPy related solutions please. Thank you.

Upvotes: 2

Views: 103

Answers (6)

jrjc
jrjc

Reputation: 21883

You could do that, no ?

print "Source =", list[0]
print "Intermediate Destination =", list[1], "\n"
for Source, Destination in zip(list[1:-1], list[2:-1]):
    print "Intermediate Source =", Source
    print "Intermediate Destination =", Destination, "\n"       
print "Intermediate Source =", list[-2]
print "Final Destination =", list[-1]

Source = 1
Intermediate Destination = 2 

Intermediate Source = 2
Intermediate Destination = 3 

Intermediate Source = 3
Final Destination = 4

Upvotes: 2

Mike Müller
Mike Müller

Reputation: 85492

This works:

from __future__ import print_function


def show_linked(lst):
    if len(lst) < 2:
        raise ValueError('List must have least 2 elements. {} found'.format(len(lst)))
    pairs = list(zip(lst, lst[1:])) 
    source, destination = pairs[0]
    print ("Source:", source)
    if len(lst) > 2:
        print ("Intermediate destination:", destination)
        print()
        for source, destination in pairs[1:-1]:
            print("Intermediate Source:", source)
            print("Intermediate destination:", destination)
            print()
        source, destination = pairs[-1]
        print("Intermediate Source:", source)
    print("Final destination:", destination)

Test:

>>> show_linked([1, 2])
Source: 1
Final destination: 2

>>> show_linked([1, 2, 3])
Source: 1
Intermediate destination: 2

Intermediate Source: 2
Final destination: 3

>>> show_linked([1, 2, 3, 4])
Source: 1
Intermediate destination: 2

Intermediate Source: 2
Intermediate destination: 3

Intermediate Source: 3
Final destination: 4

Upvotes: 1

KevinShaffer
KevinShaffer

Reputation: 858

Use enumerate with zip to count the iterations through your loop.

a = [1,2,3,4]
for idx,(i,j) in enumerate(zip(a,a[1:])):
    if idx == 0:
        print 'Source = ',i
    else:
        print 'Intermediate Source =',i
    if idx == len(a[1:])-1:
        print 'Final Destination =',j
    else:
        print 'Intermediate desintation =',j
    print

This will give you the output:

Source =  1
Intermediate desintation = 2

Intermediate Source = 2
Intermediate desintation = 3

Intermediate Source = 3
Final Destination = 4

Upvotes: 0

xtofl
xtofl

Reputation: 41519

This may be the most intuitive way:

  def print_path(link, *state):
      print("{}Source: {}".format(state[0], link[0]))
      print("{}Destination: {}".format(state[1], link[1]))

  links = list(zip(your_list, your_list[1:]))
  print_path(links[0], "", "Intermediate ")

  for link in links[1:-1]:
    print_path(link, "Intermediate ", "Intermediate ")

  print_path(links[-1], "Intermediate ", "Final ")

Upvotes: 0

Duncan
Duncan

Reputation: 95712

The simplest way is to use enumerate and check for whether the source is the first element and whether the destination is the last:

>>> your_list = [1,2,3,4]
>>> for index, Source in enumerate(your_list[:-1]):
     print("{}Source: {}".format("Intermediate " if index != 0 else "",Source))
     print("{}Destination: {}\n".format("Intermediate " if index != len(your_list)-2 else "",your_list[index+1]))


Source: 1
Intermediate Destination: 2

Intermediate Source: 2
Intermediate Destination: 3

Intermediate Source: 3
Destination: 4

>>> your_list = [1,2]
>>> for index, Source in enumerate(your_list[:-1]):
     print("{}Source: {}".format("Intermediate " if index != 0 else "",Source))
     print("{}Destination: {}".format("Intermediate " if index != len(your_list)-2 else "",your_list[index+1]))


Source: 1
Destination: 2

Upvotes: 0

eskaev
eskaev

Reputation: 1128

You can keep track of the index with enumerate:

lst = [1, 2, 3, 4]

for i, (src, dst) in enumerate(zip(lst, lst[1:])):
    src_header = 'Source' if i == 0 else 'Intermediate source'
    dst_header = 'Final destination' if i == len(lst) - 2 else 'Intermediate destination'
    print '{} = {}'.format(src_header, src)
    print '{} = {}\n'.format(dst_header, dst)

Upvotes: 0

Related Questions