Mohammad Yasin
Mohammad Yasin

Reputation: 31

ValueError using itertools.zip_longest (fillvalue)?

I have the following code and face two problems.

import itertools

data_1 = [(1, '1', '2', '3'), (2, '4', '5', '6')]
data_2 = [(1, '7', '8', '9')]

for (a, b) in itertools.zip_longest(data_1, data_2, fillvalue="----"):
    p = (a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3])
    print("p", p)
    value1 = float(p[1])+float(p[2])+float(p[3])
    print("value1", value1)

My first problem is that when I use fillvalue="----" then it's work. Why not its work when I use fillvalue="-"?

My second problem is that when I add an extra line (value2 = float(p[4])+float(p[5])+float(p[6])) below the line value1 the its give the following error message:

value2 = float(p[4])+float(p[5])+float(p[6]) p (2, '4', '5', '6', '-', '-', '-', '-') ValueError: could not convert string to float: '-'

What is my soluation, How can I solve the problem?

Upvotes: 0

Views: 111

Answers (1)

S.B
S.B

Reputation: 16526

First, think about what "zip_longest" does. It is like the zip() function but will not terminate if it reach to the end of shortest iterator, instead it continues the end of the longest and fill the shorter ones with the fillvalue.

The error you get when you specify fillvalue="-":

Your first iterator is data_1 with one item and second is data_2 with two items inside. b gets items from data_2 after unpacking. In the second iteration, it gets the fillvalue which is "-". The point is "-" is now actually your whole b and there is only one character so you can't do b[1], b[2] and etc.

I think you get the idea about your second question. In the second iteration(when you use "----"), although you can get the items p[4], p[5] and ... it can't convert "-" to float.

Upvotes: 1

Related Questions