Ad

How To Use Two Different .format() With Using One For-loop

- 1 answer

So I have been trying to figure out how I can print out two different formats using one for loop. I would like to provide the code before explaining my issue

fullList = [
  {
    'url': 'www.randomsite.com/251293',
    'numbers': '7.5'
  },
  {
    'url': 'www.randomsite.com/251294',
    'numbers': '8'
  },
  {
    'url': 'www.randomsite.com/251295',
    'numbers': '8.5'
  },
  {
    'url': 'www.randomsite.com/251296',
    'numbers': '9'
  },
  {
    'url': 'www.randomsite.com/251297',
    'numbers': '9.5'
  }
]

#fullList = [
#  {
#    'numbers': '7.5'
#  },
#  {
#    'numbers': '8'
#  },
#  {
#    'numbers': '8.5'
#  },
#  {
#    'numbers': '9'
#  },
#  {
#    'numbers': '9.5'
#  }
#]

try:
    numbersList = []
    for numbers in fullList:
        numbersList.append('{}{}'.format('{}'.format(numbers.get('url') if numbers.get('url') else ''), numbers.get('numbers')))

    print(numbersList)
except Exception:
    pass

and what I am looking for outcome is:

If url is in the list: print('<url|numbers>') meaning the format would be <url|numbers>

If no url is in the list: print(numbers) and the print here should only give the numbers - I sometimes just want the numbers, meaning that in the list I removed all URL's so it will only remain numbers.

My problem is that I dont know how I can combine these two into one format. So far I am able to print out only numbers with the code I have provided.

Ad

Answer

Use normal if/else. It will be more readable. And you have only one format.

for numbers in fullList:
    if numbers.get('url'):
        numbersList.append('{}|{}'.format(numbers.get('url'), numbers.get('numbers'))
    else:
        numbersList.append(numbers.get('numbers'))
Ad
source: stackoverflow.com
Ad