John Amraph
John Amraph

Reputation: 461

Python: split and select the best one for undefined number of entries

Sorry if the question is silly... I am looking for the trick in python that allow splitting the line and selecting the best value and the corresponding source, but the actual number of entries is unknown, it can be from 1 up to 100.

x = "32.1 (PDBbind), 50.1 (BDB), 83.0 (BMOAD_4832)"
for i in x.split(","):
    b = []
    if float(i.split()[0]) < float(b[0]):
        b = i.split()[0]

I get an error "List index out of range".

Upvotes: 0

Views: 135

Answers (2)

UltraInstinct
UltraInstinct

Reputation: 44454

The problem is here:

b = []
if float(i.split()[0]) < float(b[0]):
                              #^ b is an empty list, b[0] will raise that error

If I understand your problem right, concise solution to this would be:

>>> max(x.split(","), key=lambda x: float(x.split()[0]))
' 83.0 (BMOAD_4832)'

Upvotes: 3

MattH
MattH

Reputation: 38255

You're getting List index out of range because b = [] and then float(b[0]).

Upvotes: 1

Related Questions