Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip in python does not work properly with lists

Here is what I tried:

>>> d
array([ 0.71428573,  0.69230771,  0.69999999], dtype=float32)
>>> f
[('name', 999), ('ddd', 33), ('mm', 112)]
>>> for n1,s1,normal in zip(d,f):
...     print(n1,s1,normal)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

Then I tried this:

>>> for (name,confidence),normal in zip(d,f):
...     print(name,confidence,normal)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'numpy.float32' object is not iterable

Where,

d = ['Jonathan Walsh','Patrick Walsh','John Welsh']
array = np.array(d)
from pyxdameraulevenshtein import damerau_levenshtein_distance_ndarray, normalized_damerau_levenshtein_distance_ndarray
 d = normalized_damerau_levenshtein_distance_ndarray('jwalsh', array)

Kindly, let me know what i need to do to print the values simultenously? I am using Python2.7.13 on Windows 10.

like image 347
Jaffer Wilson Avatar asked Aug 18 '26 01:08

Jaffer Wilson


1 Answers

f is a nested list, hence to unpack its item to individual variables you need to do:

>>> for n1, (s1, normal) in zip(d, f):
...     print(n1, s1, normal)
...
(0.71428573, 'name', 999)
(0.69230771, 'ddd', 33)
(0.69999999, 'mm', 112)

This is basically equivalent to:

>>> a, (b, c) = [1, (2, 3)]
>>> a, b, c
(1, 2, 3)

While this will fail because a can assigned to 1 but now for b and c there's only one item and Python complains that it needs one more item in the list on RHS or we use the same structure on LHS.

>>> a, b, c = [1, (2, 3)]
Traceback (most recent call last):
  File "<ipython-input-9-c8a9ecc8f325>", line 1, in <module>
    a, b, c = [1, (2, 3)]
ValueError: need more than 2 values to unpack

From docs:

If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

like image 159
Ashwini Chaudhary Avatar answered Aug 20 '26 14:08

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!