0

I want to cycle values in a loop but also using the zip function, however the catch is to manipulate those values that are cycled. In this case, if the values are cycled then return a string "None" instead.

For example:

data = {
    'carNumbers':[
    1, 2, 3, 2, 3, 2, 1, 3
    ],
    'bikeNumbers':[
        4, 3, 5
    ],
    'otherNumbers':[
        2
    ]
       }

I can do the following:

from itertools import cycle
test={}
for car, bike, other in zip(data['carNumbers'],cycle(data['bikeNumbers']),cycle(data['otherNumbers'])):
    print(other)

2 2 2 2 2 2 2 2

However, because other has a shorter length than the largest length car those extra values should return the following:

2 "None" "None" "None" "None" "None" "None" "None"

dollar bill
  • 258
  • 1
  • 9
  • 2
    I believe this should answer your question https://stackoverflow.com/questions/1277278/is-there-a-zip-like-function-that-pads-to-longest-length – Sam Feb 01 '22 at 17:18
  • What you describe doesn't sound like "cycling" the values at all. It seems like you want a *single* iteration over the `carNumbers` data. If, having padded out the data so that there are 8 values for each kind of `data`, you want to repeat those 8 values, *then* you can apply `cycle` *to the overall `zip` result*. – Karl Knechtel Feb 01 '22 at 18:32
  • 1
    @Sam in the future, if you believe that to be the case, please vote to close the question as a duplicate. – Karl Knechtel Feb 01 '22 at 18:34
  • @KarlKnechtel After reviewing the answer I have a slight issue, the None values are not returned as a string - how can I return these None values as string which Is actually what I wanted as shown in the post. – dollar bill Feb 01 '22 at 21:27
  • If you want the string `"None"`, then specify that as the `fillvalue`, as explained in the documentation. – Karl Knechtel Feb 01 '22 at 23:00

1 Answers1

2

You can use itertools.zip_longest to handle this case, with this function, the missing values will be replaced with whatever you pass to the fillvalue argument (defaults to None).

list(itertools.zip_longest(data['carNumbers'],data['bikeNumbers'],data['otherNumbers'], fillvalue='value'))
rentox98
  • 361
  • 1
  • 4
  • 10