Skip to content
Advertisement

if statement for columns in 2D list

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.

Advertisement

Answer

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)]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement