2

The task is to convert [1.5, 1.2, 2.4, 2.6, 3.0, 3.3] into [(2, 1), (2, 3), (3, 3)]

Currently I use a bruteforce way to do it:

result = []
for i in range(0, len(nums), 2):
   x = int(round(nums[i]))
   y = int(round(nums[i + 1]))
   result.append((x,y))
return result

Is there a more concise built in solution (e.g., using itertoools)?

Alex
  • 579
  • 1
  • 6
  • 14
  • Possible duplicate of [What is the most "pythonic" way to iterate over a list in chunks?](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) – pault Apr 02 '19 at 15:25
  • 2
    I'm sure this is a dupe, but you could just `zip` `lst[::2]` and `lst[1::2]` – JohnE Apr 02 '19 at 15:26
  • 1
    Also, there's nothing wrong with the way you're doing it. – pault Apr 02 '19 at 15:27

4 Answers4

2

You can zip them together (using the alternating patterns [::2] and [1::2]) and then round as you go:

L = [1.5, 1.2, 2.4, 2.6, 3.0, 3.3]
L = [(round(x), round(y)) for x, y in zip(L[::2], L[1::2])]
# [(2, 1), (2, 3), (3, 3)]
Alex
  • 6,610
  • 3
  • 20
  • 38
2

You can use iter() with zip() to create pairs. And later you can round values.

I will use code from @Alex answer to show difference

L = [1.5, 1.2, 2.4, 2.6, 3.0, 3.3]
it = iter(L)
L = [(round(x), round(y)) for x, y in zip(it, it)]
furas
  • 134,197
  • 12
  • 106
  • 148
0

Assuming that the given list is always made of even number of elements:

l = [1.5, 1.2, 2.4, 2.6, 3.0, 3.3]

def f(s):
    for i in range(int(len(s)/2)):
        yield (round(s[2*i]), round(s[2*i+1]))

print(list(f(l)))

#[(2, 1), (2, 3), (3, 3)]
New2coding
  • 715
  • 11
  • 23
0

I've got a solution using zip. You can try this too.

l = [1.1,2.2,3.3,4.4,5.5,6.6]
def fun(l):
    x = list(zip(*[l[i::2] for i in range(2)]))
    print(x)

ll = round[(x) for x in l]
fun(ll)

#[(1, 2), (3, 4), (6, 7)]
Protik Nag
  • 511
  • 5
  • 20