user7926701
user7926701

Reputation:

Pythonic way of looping values into variables

So I've completed a project I was working on but I'm trying to find a way to make it more pythonic in a sense that takes less lines and well looks cleaner. I've been told before that if it isn't broken it shouldn't be fix but always looking for a better way to improve my programming.

So I have a tuple n with these values:

n = ((100,200), (300,400),(500,600)) for i, x in enumerate(n): if i is 0: D = x[0] if i is 1: M = x[0] if i is 2: s = x[0] print D, M, s

where (D, M, s) should print out:

100, 300, 500

Is there a way to write those if statement since they are all going to be the first value always every time it loops through the tuple?

Upvotes: 1

Views: 57

Answers (4)

Martin Evans
Martin Evans

Reputation: 46759

You could use a list comprehension as follows:

n = ((100,200), (300,400), (500,600))    
print ', '.join([str(v1) for v1, v2 in n])

This would display:

100, 300, 500

It will also work when n is a different length.

Upvotes: 1

gushitong
gushitong

Reputation: 2026

Like this:

D, M, s = zip(*n)[0]

Upvotes: 0

Ralph Caraveo
Ralph Caraveo

Reputation: 10225

You can leverage unpacking to accomplish this along with a list comprehension:

D, M, s = [x[0] for x in n]

This effectively loops through the list of tuples taking the first item and resulting in a list that now looks like: [100, 300, 500]

This is then unpacked in: D, M, s

Notice that the code is very simple, easy to read and doesn't require any other constructs to make it work.

Upvotes: 2

rohan
rohan

Reputation: 113

n=((100,200),(300,400),(500,600))
D,M,s=n[0][0],n[1][0],n[2][0]
print(D,M,s,sep=" ,")

Upvotes: 0

Related Questions