I want to create a list of paired numbers. For example, I have a list of numbers as follows:
a = [1, 4, 7, 10, 13, 16, 19, 21, 24, 27, 30]
I want to create a paired list like this:
paired_list_a = [[1,3],[4,6],[7,9],[10,12],[13,15],[16,18],[19,20],[21,23],[24,26],[27,29]]
That is, I want to skip the first element and pair the numbers with the one next to them with minus one.
I tried something like this but no luck
paired_list_a = [1, 4, 7, 10, 13, 16, 19, 21, 24, 27, 30]
row = [[a[i],a[i+1]-1] for i in range(len(a))]
but it is throwing IndexError: list index out of range
Can anyone help me with this?
Use zip here with all values of same list without first value:
row = [[x, y - 1] for x, y in zip(a, a[1:])]
print (row)
[[1, 3], [4, 6], [7, 9], [10, 12], [13, 15], [16, 18], [19, 20], [21, 23], [24, 26], [27, 29]]
That's because the last number doesn't has a successor. You should try something like:
row = [[a[i],a[i+1]-1] for i in range(len(a)-1)]
If you have a pattern in the numbers (for example: every item is last_item + 2) you could pair the last value without the cycle.
row[-1] = [a[-1], a[-1]+2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With