PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 7, 2022

[FIXED] How to get all data from set

 November 07, 2022     list, python, set     No comments   

Issue

So, its my data in list:

[('AED', Decimal('3.67303')), ('AFN', Decimal('89.408409')), ('ALL', Decimal('118.735882')), ('AMD', Decimal('420.167855')), ('ANG', Decimal('1.803593')), ('AOA', Decimal('431.906'))]

And I did this but only for first element: Currency: AED, Value: 3.67303

 for key, val in query:
    return f'Currency: {key}, Value: {val}'

How can I do this for all?


Solution

If you want to return everything from a function create a new list with list comprehensions

def func():
    lst = [('AED', Decimal('3.67303')), ('AFN', Decimal('89.408409')), ('ALL', Decimal('118.735882')), ('AMD', Decimal('420.167855')), ('ANG', Decimal('1.803593')), ('AOA', Decimal('431.906'))]
    return [f'Currency: {key}, Value: {val}' for key, val in lst]

or use yield to create a generator

def func():
    lst = [('AED', Decimal('3.67303')), ('AFN', Decimal('89.408409')), ('ALL', Decimal('118.735882')), ('AMD', Decimal('420.167855')), ('ANG', Decimal('1.803593')), ('AOA', Decimal('431.906'))]
    for key, val in lst:
        yield f'Currency: {key}, Value: {val}'

another less explicit way to create a generator

def func():
    lst = [('AED', Decimal('3.67303')), ('AFN', Decimal('89.408409')), ('ALL', Decimal('118.735882')), ('AMD', Decimal('420.167855')), ('ANG', Decimal('1.803593')), ('AOA', Decimal('431.906'))]
    return (f'Currency: {key}, Value: {val}' for key, val in lst)

Output

for val in func():
    print(val)

Currency: AED, Value: 3.67303
Currency: AFN, Value: 89.408409
Currency: ALL, Value: 118.735882
Currency: AMD, Value: 420.167855
Currency: ANG, Value: 1.803593
Currency: AOA, Value: 431.906


Answered By - Guy
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing