if statement for columns in 2D list

Question:

I need to iterate two different lists of integers with an if-statement that requires a mathematic operation. I’ve approached this in several ways, the latest one shown below.

I have 4 lists that I’ve extracted from columns in a CSV file:

unique_names = ["Ian", "Laura", "Winona", "Garfield"]
arrivaltime = ["12:14:31", "12:15:02", "12:14:14", "13:00:00"]
score = [83, 99, 90, 100]
personalbest=[75, 100, 89, 90]

I need to identify the names for those competitors who are outperforming,
i.e. where the score > personalbest*1.1.

No imported modules allowed (except for csv).

outperforming = []
tdlist = [[arrivaltime], [unique_names], [score], [personalbest]]
for i in tdlist[2]: 
    if i*1.1 > (tdlist[3][i]): 
        outperforming.append("tdlist[1][i]")

I get this error: TypeError: can’t multiply sequence by non-int of type ‘float’

I also tried this to check for other errors:

for i in tdlist[2]: 
    if i > (tdlist[3][i]): 
        outperforming.append("tdlist[1][i]")

Then I get this error: TypeError: list indices must be integers or slices, not list.

Asked By: mycorrhiza

||

Answers:

You can use the zip function to iterate over multiple sequences at once. For example:

for name, attempt, pb in zip(unique_names, score, personal_best):
    print(name, attempt, pb)
Answered By: jprebys

Use the zip() function to group your data by index, then use an if to check the condition you want:

Code:

unique_names = ["Ian", "Laura", "Winona", "Garfield"]
arrivaltime = ["12:14:31", "12:15:02", "12:14:14", "13:00:00"]
score = [83, 99, 90, 100]
personalbest=[75, 100, 89, 90]

performers = []
for u, a, s, pb in zip(unique_names, arrivaltime, score, personalbest):
    if s > pb * 1.1:
        performers.append((u, a, s, pb))
        
print(performers)

Output:

[('Ian', '12:14:31', 83, 75), ('Garfield', '13:00:00', 100, 90)]
Answered By: Ryan

zip() solutions are certainly nice. And elegant. I would also be tempted to use enumerate(), which goes through a list and gives you the each item and the index:

for idx,x in enumerate(score):
    if s > 1.1*personalbest[idx]:
        outperforming.append(unique_names[idx])
    
Answered By: bfris
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.