gpt4 book ai didi

python - 我该如何修复 : "TypeError: cannot unpack non-iterable NoneType object"

转载 作者:行者123 更新时间:2023-12-05 05:53:10 27 4
gpt4 key购买 nike

我一直在通过 stackoverflow 和其他各种网站进行搜索,但我已经有大约一个星期无法解决这个错误了。

我正在尝试获取字典中每个国家/地区的最小值和最大值。字典的关键字是区域。我不确定类型错误在哪里,但如果有人能提供帮助,我将不胜感激。

这是错误:

        min_tup, max_tup = get_min_max(D,region,option)
File "proj08.py", line 107, in get_min_max
return min[0], max[0]
UnboundLocalError: local variable 'min' referenced before assignment

这是示例输入:地区,选项:北美,2

这是解释函数和 .csv 的文档 https://www.cse.msu.edu/~cse231/Online/Projects/Project08/Project08.pdf https://www.cse.msu.edu/~cse231/Online/Projects/Project08/data_short.csv

代码如下:

import csv
from operator import itemgetter
# do NOT import sys

REGION_LIST = ['East Asia & Pacific',
'Europe & Central Asia',
'Latin America & Caribbean',
'Middle East & North Africa',
'North America',
'South Asia',
'Sub-Saharan Africa']

PROMPT = "\nSpecify a region from this list or 'q' to quit -- \nEast
Asia & Pacific,Europe & Central Asia,Latin America & Caribbean,Middle
East & North
Africa,North America,South Asia,Sub-Saharan Africa: "


def open_file():
# Opens a file
while True:
try:
file = input("Input a file: ")
fp = open(file, "r")
return fp
except FileNotFoundError:
print("Invalid filename, please try again.")


def read_file(fp):

# Sets read Csv file to a variable
reader = csv.reader(fp)
# Skips the header
next(reader, None)

# Country List
country_list = []
# sets a dictionary
Dict = dict()
for line in reader:
try:
skipper = ""
if skipper in line:
continue
else:
region = line[6]
country = line[0].strip()
electricty = float(line[2])
fertility = float(line[3])
gdp = float(line[4])
life_expectancy = float(line[5])

country_list = [country, electricty, fertility, GDP,
life_expectancy]

if region in Dict.keys():
Dict[region].append(country_list)
elif region not in Dict.keys():
Dict[region] = [country_list]
else:
continue

except KeyError:
continue
except ValueError:
continue

return Dict


def get_min_max(Dict, region, option):
lis = []
for k, v in Dict.items():
if region in k[0]:
if option == 1:
electricity = v[1]

tup = tuple(k, electricity)
lis.append(tup)

min = sorted(lis, key=itemgetter(1))
max = sorted(lis, key=itemgetter(1), reverse=True)

if option == 2:
fertility = v[2]

tup = tuple(k, fertility)
lis.append(tup)

min = sorted(lis, key=itemgetter(1))
max = sorted(lis, key=itemgetter(1), reverse=True)

if option == 3:
gdp = v[3]

tup = tuple(k, gdp)
lis.append(tup)

min = sorted(lis, key=itemgetter(1))
max = sorted(lis, key=itemgetter(1), reverse=True)

if option == 4:
life_expectancy = v[4]

tup = tuple(k, life_expectancy)
lis.append(tup)
min = sorted(lis, key=itemgetter(1))
max = sorted(lis, key=itemgetter(1), reverse=True)

return min[0], max[0]


def display_all_countries(D, region):

if region in REGION_LIST:

if region == 'all':
print("\nDisplaying {} Region:\n".format(region))
print("{:32s}{:>20s}{:>20s}{:>17s}{:>18s}".format(
"Country", "Electricity Access", "Fertility rate", "GDP
per capita", "Life expectancy"))
for k, v in D.items():
if region in v[0]:
country = v[0]
electricity = v[1]
fertility = v[2]
gdp = v[3]
life = v[4]
tup = (country, electricity, fertility, gdp, life)

sorted(tup, key=itemgetter(0), reverse=True)
print("{:32s}{:>20.2f}{:>20.2f}{:>17.2f}
{:>18.2f}".format(
tup[0], tup[1], tup[2], tup[3], tup[4]))

if region not in REGION_LIST:
return None


def get_top10(D):
pass


def display_options():
"""
DO NOT CHANGE
Display menu of options for program
"""
OPTIONS = """\nMenu
1: Minimum and Maximum Countries Access to Electricity
2: Minimum and Maximum Countries Fertility Rate
3: Minimum and Maximum Countries GDP per Capita
4: Minimum and Maximum Countries Life Expectancy
5: List of countries in a region
6: Top 10 Countries in the world by GDP per Capita\n"""
print(OPTIONS)


def main():
file = open_file()
# while True:
# if user == 'East Asia & Pacific' or user == 'Europe &
Central Asia' or user == 'Middle East & North Africa' or user ==
'Latin America & Caribbean' or user == 'North America' or user ==
'South Asia' or user == 'Sub-Saharan Africa':
# print("\nRegion: ".format(user))
# display_options()

# if user == "Q" or user == "q":
# break
# else:
# user = input(PROMPT)
region = 'North America'
option = '2'
superD = read_file(file)
mina = get_min_max(superD, region, option)

#print(mina)

if __name__ == '__main__':
main()

最佳答案

错误是告诉你不能使用解包赋值,例如

x, y = function()

因为该函数返回了一些无法解压的东西(在本例中为无)这意味着您的函数以某种方式返回 None 。如果没有可重用的示例,我们不能肯定地说,但我猜这是因为函数中的第一个 if 条件可以返回 None。

虽然允许,但在 python 函数中有多个不同的返回类型通常不是一个好主意。这是因为调用者必须知道如何处理函数可能做的不同事情,而不是能够相信函数会工作并给他们一个好的答案(当然,假设他们使用的是正确的输入。)

关于python - 我该如何修复 : "TypeError: cannot unpack non-iterable NoneType object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69956067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com