Saturday, March 16, 2013

izip() explained

Input:Give two Iterators Output:Get a tuple of combined iterators.
#!usr/bin/env/python
"""izip() returns an iterator(lists,strings,tuples,files are iterators geneally.)
 that combines the elements of several iterators 
 into tuples."""
from itertools import *
 #Example 1(with equal sized lists)
print "Equal Sized lists:"
#==>Out put will always be a tuple for izip()

for i in izip([1,2,3],['a','b','c']):
  print i,
print "\nUnEqual Sized lists:"
#==>Out put will always be a tuple for izip()
for i in izip([1,2,3],['x','y']):
  print i,
print "\nUnequal Sized tuples:"
#==>Out put will always be a tuple for izip()
for i in izip((1,2,3,4,5),(99,100)):
  print i,
Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

1 comment:

  1. I am trying to create a "pivot table". I found izip works when I feed it discrete tuples. However, I can not get it to work using one large string.
    Thank you in advance.
    ----------------------------------------------------------------------------------------------
    from itertools import *

    print "OLD"
    a1="cluster_a01","15","None","None"
    a2="cluster_a02","6","None","None"
    a3="cluster_a03","4","None","1"
    for i in izip (a1,a2,a3):
    print i

    print "********************************"

    print "NEW"
    n = 0
    s = '''"cluster_b01","15","None","None"
    "cluster_b02","6","None","None"
    "cluster_b03","4","None","1"'''
    t = s.split("\n")
    my_tuple = tuple(t)
    for j in izip (my_tuple):
    print j
    ====================================
    OUTPUT:
    ====================================
    OLD :-)
    ('cluster_a01', 'cluster_a02', 'cluster_a03')
    ('15', '6', '4')
    ('None', 'None', 'None')
    ('None', 'None', '1')
    *************************************
    NEW :-(
    ('"cluster_b01","15","None","None"',)
    ('"cluster_b02","6","None","None"',)
    ('"cluster_b03","4","None","1"',)

    ReplyDelete