1

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?

Martin Evans
  • 45,791
  • 17
  • 81
  • 97

4 Answers4

2

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.

Ralph Caraveo
  • 10,025
  • 7
  • 40
  • 52
1

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.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
  • i would like suggest to use **list comprehension** with ``join`` instead of **generator expression** since its more efficient http://stackoverflow.com/a/9061024/7742341 – Luchko Apr 26 '17 at 17:18
0
n=((100,200),(300,400),(500,600))
D,M,s=n[0][0],n[1][0],n[2][0]
print(D,M,s,sep=" ,")
rohan
  • 113
  • 1
  • 1
  • 6
  • 1
    Please add more information and context. What does this code do and how does this answer the user's question? If you're going to make a code-only answer, the code needs to at least be well commented. – Al Sweigart Apr 26 '17 at 18:58
0

Like this:

D, M, s = zip(*n)[0]
gushitong
  • 1,898
  • 16
  • 24