jhon_wick
jhon_wick

Reputation: 247

Print values from several array using Python

I have an array of numbers. For example:

a = (1,2,3,4,5,6)

Now I need to create another two array from a based on some criteria. Say x array of even number numbers and y array of odd numbers.

I have done that. But the next thing is, I want to publish them as below:

z   x   y
1       1
2   2  
3       3
4   4
5       5
6   6

I dont know how to print the void places as I have already created x and y array from z. Any help?

Upvotes: 1

Views: 68

Answers (3)

kvorobiev
kvorobiev

Reputation: 5070

You can use following code

a = (3, 2, 3, 4, 5, 6)
print "z\tx\ty"
for i,e in enumerate(a):  
    print i, "\t"*(i%2+1), e

This is a shorter version of solution proposed by Red Shift.

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

You can use a simple indexing :

>>> a =np.array([1,2,3,4,5,6])
>>> x,y=a[0::2],a[1::2]
>>> x
array([1, 3, 5])
>>> y
array([2, 4, 6])

Or as a more general way to applying a condition on your array you can use np.where :

>>> np.where(a%2!=0)[0]
array([0, 2, 4])
>>> 
>>> np.where(a%2==0)[0]
array([1, 3, 5])

Upvotes: 0

Red Shift
Red Shift

Reputation: 1312

The way to print a large space is to insert a tab. This is simply done by printing "\t" which represents a tab character.

This code does it:

a = (1, 2, 3, 4, 5, 6)
print "z\tx\ty"  # Print top line separated by tab characters
for i in a:  # For each element in the list
    if i % 2 == 0:  # If the element is even
        print i, "\t", i
    else:  # If it is odd
        print i, "\t\t", i

Output:

z   x   y
1       1
2   2
3       3
4   4
5       5
6   6

Upvotes: 1

Related Questions