I have 2 lists
[902920,28393892,93993992,93938939929,929393993928,38982933939393, 883383938393]
[1.9, 1,7, 1,6]
Basically 1.9
links to 902920,28393892,93993992
1.7
links to 93938939929,929393993928,38982933939393
In the for loop I need to
request.get(1.9
, then the 3 numbers from the first list)
then 1.7
and the next 3 numbers
Anyway to make this link?
Sorry I should mention 1.6 could be linked to the next 2 numbers in the list, and another number 1.5 could be linked to the next 7.
CodePudding user response:
more-itertools
has this grouper
function that could be useful for this task. I replicate it here:
from itertools import zip_longest
def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
"Collect data into non-overlapping fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
args = [iter(iterable)] * n
if incomplete == 'fill':
return zip_longest(*args, fillvalue=fillvalue)
if incomplete == 'strict':
return zip(*args, strict=True)
if incomplete == 'ignore':
return zip(*args)
else:
raise ValueError('Expected fill, strict, or ignore')
This function combined with zip
(documentation) in the way shown below returns an iterator of tuples where the first element of the tuple is an element from b
and the second element of the tuple is a tuple of three elements taken from a
. For this example, the iterator returned by zip
links 1.9
to the first three elements of a
, 1.7
to the next three elements of a
, and so on.
a = [902920,28393892,93993992,93938939929,929393993928,38982933939393, 883383938393]
b = [1.9, 1.7, 1.6]
c = zip(b, grouper(a, 3))
for item in c:
print(item)
Output
(1.9, (902920, 28393892, 93993992))
(1.7, (93938939929, 929393993928, 38982933939393))
(1.6, (883383938393, None, None))
The grouper
function offers additional functionality. By default, where there are not enough elements left from the long a
list to fill a 3-tuple, the empty elements will be filled with None
. So you can set fillvalue
to something else should you prefer to obtain a value other than None
or you could even state that you do not want incomplete tuples as in this example
c = zip(b, grouper(a, 3, incomplete = 'ignore'))
for item in c:
print(item)
Output
(1.9, (902920, 28393892, 93993992))
(1.7, (93938939929, 929393993928, 38982933939393))