Python Forum
What does ty(val) mean?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What does ty(val) mean?
#1
In the following code:
>>> line='yosi, 1, 3.14'
>>> types=[str, int, float]
>>> raw=line.split(',')
>>> raw
['yosi', ' 1', ' 3.14']
>>> fields = [ty(val) for ty,val in zip(types,raw)]
>>> fields
['yosi', 1, 3.14]
What do ty and val refer to?
Reply
#2
zip(types,raw) create an iterator that produces tuples of the form (x, y)
>>> >>> list(zip(types,raw))
[(<class 'str'>, 'yosi'), (<class 'int'>, ' 1'), (<class 'float'>, ' 3.14')]
>>> for ty,val in zip(types,raw):
...   print("ty:",ty,"val:",str(val))
...
ty: <class 'str'> val: yosi
ty: <class 'int'> val:  1
ty: <class 'float'> val:  3.14
Reply
#3
zip(types, raw) will yield 2-element tuples, where each tuple element at index 0 comes from types list and element at index 1 comes from raw list.
Then you unzip each tuple into 2 names - ty and val.
Then you use the function ty to convert val (which is initially str) to respective type.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020