简体   繁体   中英

how to zip non iterables

I want to display the maximum values of Africa from [1995-2001] and [2002-2008] and the years they occurred my current code is as follows:

year = [1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008]
africa = [1045,928,947,987,1092,1764,1266,1444,1764,2313,2989,3668,4146,7293]
max1 = max(africa[0],africa[1],africa[2],africa[3],africa[4],africa[5],africa[6])

max2 = max(africa[7],africa[8],africa[9],africa[10],africa[11],africa[12],africa[13])

for Max1, Year in zip (max1, year):
    print("The maximum export value to Africa over [1995-2001] was {Max1} and the year it occurred was {Year}")
for Max2, Year in zip (max2, year):
    print("The maximum export value to Africa over [2002-2008] was {Max2} and the year it occurred was {Year}")

I'm currently getting a TypeError because zip argument #1 doesn't support iteration. Is there a way to zip them or a better way to do this?

You don't need zip for that since you are calculating max . zip takes iterables, but max1 or max2 is not iterable, it is integer. You need to index it properly. Also make sure use s-string properly

year = [1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008]
africa = [1045,928,947,987,1092,1764,1266,1444,1764,2313,2989,3668,4146,7293]
max1 = max(africa[0:7])

max2 = max(africa[7:])

# for Max1, Year in zip(max1, year):
print(f"The maximum export value to Africa over [1995-2001] was {max1} and the year it occurred was {year[africa.index(max1)]}")
# for Max2, Year in zip(max2, year):
print(f"The maximum export value to Africa over [2002-2008] was {max2} and the year it occurred was {year[africa.index(max2)]}")
The maximum export value to Africa over [1995-2001] was 1764 and the year it occurred was 2000
The maximum export value to Africa over [2002-2008] was 7293 and the year it occurred was 2008

But if you want to use zip anyway

year = [1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008]
africa = [1045,928,947,987,1092,1764,1266,1444,1764,2313,2989,3668,4146,7293]

data = list(zip(year, africa))

m1 = max(data[0:7], key=lambda x: x[1])
m2 = max(data[7: ], key=lambda x: x[1])

print(f"The maximum export value to Africa over [1995-2001] was {m1[1]} and the year it occurred was {m1[0]}")

print(f"The maximum export value to Africa over [2002-2008] was {m2[1]} and the year it occurred was {m2[0]}")
The maximum export value to Africa over [1995-2001] was 1764 and the year it occurred was 2000
The maximum export value to Africa over [2002-2008] was 7293 and the year it occurred was 2008

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM