Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 676

Swapping list elements effectively in Python

I have a Python list as follows:-

l=['EUR/USD',
 'USD/JPY',
 'GBP/USD',
 'USD/CAD',
 'AUD/USD',
 'NZD/USD',
 'USD/CHF',
 'USD/NOK',
 'USD/SEK']

I want the base currency to be USD. This means the first element of l would be USD/EUR. Following code works but I was wondering if there is a better way of doing it.

l2=[]
for x in range(len(l)):
    l2.append(l[x].split('/'))

k=pd.DataFrame(l2)

for i in range(len(k)):

    if k.iloc[i,0]=='USD':
        print("base currency is USD")

    else:
        print("Base currency is not USD. Making it base currency")
        temp=k.iloc[i,0]
        k.iloc[i,0]='USD'
        k.iloc[i,1]=temp

Upvotes: 1

Views: 65

Answers (3)

aydow
aydow

Reputation: 3801

Define a function to invert the pair and then use map

In [759]: def usd_base(ccy):
     ...:     delimiter = '/'
     ...:     base, term = ccy.split(delimiter)
     ...:     if base != 'USD' and term == 'USD':
     ...:         return delimiter.join((term, base))
     ...:     return ccy
     ...:

In [760]: list(map(usd_base, l))
Out[760]:
['USD/EUR',
 'USD/JPY',
 'USD/GBP',
 'USD/CAD',
 'USD/AUD',
 'USD/NZD',
 'USD/CHF',
 'USD/NOK',
 'USD/SEK']

If you're not already using a DataFrame, there's probably no reason to create one just for this purpose for a list of that size

For Python 2 you can just use

map(usd_base, l)

Upvotes: 2

Rahul K P
Rahul K P

Reputation: 16081

You can archive with endswith + split + join

['/'.join(i.split('/')[::-1]) if i.endswith('USD') else i for i in l]

Result

['USD/EUR',
 'USD/JPY',
 'USD/GBP',
 'USD/CAD',
 'USD/AUD',
 'USD/NZD',
 'USD/CHF',
 'USD/NOK',
 'USD/SEK']

Upvotes: 2

timgeb
timgeb

Reputation: 78690

I'd write it like this, which IMO is a bit more readable.

>>> l=['EUR/USD', 'USD/JPY', 'GBP/USD', 'USD/CAD', 'AUD/USD', 'NZD/USD', 'USD/CHF', 'USD/NOK', 'USD/SEK']
>>>
>>> result = []
>>> delim = '/'
>>> for currencies in l:
...:    first, second = currencies.split(delim)
...:    if first == 'USD':
...:        result.append(currencies)
...:    else:
...:        result.append(delim.join((second, first)))
...:        
>>> result
>>> 
['USD/EUR',
 'USD/JPY',
 'USD/GBP',
 'USD/CAD',
 'USD/AUD',
 'USD/NZD',
 'USD/CHF',
 'USD/NOK',
 'USD/SEK']

As a general tip, avoid using explicit indices when iterating like the plague. Often there is a more readable solution than indexing into your datastructure with integers (not always, of course).

Here's a cool video: Loop like a native: while, for, iterators, generators

Upvotes: 4

Related Questions