从外部范围重新定义名称并考虑使用枚举而不是迭代

2024-10-16 20:49:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在代码中使用了pylint,实现了8.63,但是我需要一个10。你会注意到我最大的问题是:

  • C0200:考虑使用枚举而不是用范围和LeN迭代(考虑使用枚举)
  • W0621:从外部范围(第10行)重新定义名称“状态”(重新定义外部名称)

另外,当我试图用逗号更正问题时,我的代码不再有效。我一直是python的初学者,我已经学习了2周了,我很震惊我能理解这么多。但我想变得更好。我做错了什么

import sys
import matplotlib.pyplot as plt
#List of states, capitals, populations, and flower
states = [
    ('California', 'Sacremento ', 39512223, 'Golden Poppy '),
    ('Alabama', 'Montgomery', 4903185, 'Camellia'),
    ('Alaska', 'Juneau', 731545, 'Forget-Me-Not'),
    ('Arizona', 'Phoenix', 7278717, 'Suguaro Catus Blossom'),
    ('Arkansas', 'Little Rock', 3017825, 'Apple Blossom'),
    ('Colorado', 'Denver ', 5758736, 'Mountain Columbine '),
    ('Connecticut', 'Hatford ', 3565287, 'Mountain Laurel '),
    ('Delaware', 'Dover ', 973764, 'Peach Blossom '),
    ('Florida', 'Tallahassee ', 21477737, 'Orange Blossom '),
    ('Georgia  ', 'Atlanta ', 10617423, 'Cherokee Rose '),
    ('Hawaii  ', 'Honolulu ', 415872, 'Red Hibiscus '),
    ('Idaho  ', 'Boise ', 1787065, 'Syringa '),
    ('Illinois  ', 'Springfield ', 12671821, 'Violet '),
    ('Indiana  ', 'Indianaplois ', 6732219, 'Peony '),
    ('Iowa  ', 'Des Moines ', 3155070, 'Wild Rose '),
    ('Kansas  ', 'Topeka ', 2913314, 'Sunflower '),
    ('Kentucky  ', 'Frankfort ', 4467673, 'Goldenrod '),
    ('Louisiana  ', 'Baton Rouge ', 4648794, 'Magnolia '),
    ('Maine  ', 'Augusta ', 1344212, 'Pine Cone & Tassel '),
    ('Tennessee  ', 'Nashville ', 6833174, 'Iris '),
    ('Maryland  ', 'Annapolis,  ', 6045680, 'Black-eyed Susan '),
    ('Deleware  ', 'Dover ', 973764, 'Peach Blossom '),
    ('Massachusettes  ', 'Boston ', 6949503, 'Mayflower '),
    ('Rhode_Island  ', 'Providence ', 1059361, 'Violet '),
    ('Minniesota  ', 'St.Paul ', 5639632, 'Lady-Slipper '),
    ('Mississippi  ', 'Jackson ', 2976149, 'Magnolia '),
    ('Missouri  ', 'Jefferson City ', 6137428, 'Hawthorne '),
    ('Michigan  ', 'Lansing ', 9986857, 'Apple Blossom '),
    ('Montana  ', 'Helena ', 1068778, 'Bitterroot '),
    ('Nebraska  ', 'Lincoln ', 1934408, 'Goldenrod '),
    ('Nevada  ', 'Carson City ', 3080156, 'Sagebrush '),
    ('New_Hampshire  ', 'Concord ', 1359711, 'Purple Lilac '),
    ('Vermont  ', 'Montpelier ', 623989, 'Red Clover '),
    ('New_Jersey  ', 'Trenton ', 8882190, 'Violet '),
    ('New_Mexico  ', 'Santa Fe ', 2096829, 'Yucca '),
    ('New_York  ', 'Albany ', 19453561, 'Rose '),
    ('North_Carolina  ', 'Raleigh ', 10488084, 'Flowering Dogwood '),
    ('Wyoming  ', 'Cheyenne ', 78759, 'Indian Paintbrush '),
    ('North_Dakota  ', 'Bismark ', 762062, 'Prairie Rose '),
    ('Ohio  ', 'Columbus ', 11689100, 'Scalet Carnation '),
    ('Oklahoma  ', 'Oklahoma City ', 3956971, 'Mistletoe '),
    ('Oregon  ', 'Salem ', 4217737, 'Oregon Grape '),
    ('Pennsylvania  ', 'Harrisburg ', 12801989, 'Mountain Laurel '),
    ('South_Carolina  ', 'Columbia ', 5148714, 'Yellow Jessamine '),
    ('South_Dakota  ', 'Pierre ', 88465, 'Pasque flower '),
    ('Texas  ', 'Austin ', 28995881, 'Bluebonnet '),
    ('Utah  ', 'Salt Lake City ', 3202985, 'Sego Lily '),
    ('Virginia  ', 'Richmond ', 8535519, 'Dogwood '),
    ('Washington  ', 'Olympia ', 7614893, 'Coast Rhododendron '),
    ('West_Virginia  ', 'Charleston ', 1792147, 'Rhododendron '),
    ('Wisconsin  ', 'Madison ', 5822434, 'Wood Violet ')
]
def sort_func(tup, key, rev=False):
    '''Sort function to sort variable based on key'''
    tup.sort(key=lambda x: x[key], reverse=rev)
    return tup
def display_states_sorted(states):
    '''Displays the sorted states according to states list'''
    #Sorts in alphabetical order
    states = sort_func(states, 0)
    #Shows the requested state, capital, population and flower
    print("State", "Capital", "Population", "Flower")
    for i in range(0, len(states)):
        print(states[i][0], states[i][1], states[i][2], states[i][3])
def display_search_of_states(state_name):
    '''Displays requested states details'''
    state_found = 0
    print("Searching State...:", state_name)
    print("State", "Capital", "Population", "Flower")
    for i in range(0, len(states)):
        if state_name[0].strip() == states[i][0].strip().lower():
            print(states[i][0], states[i][1], states[i][2], states[i][3])
            state_found = 1
            break
    if state_found == 0:
        print("State Not Found")
def highest_5_population(states2):
    '''Displays a bar graph of the top 5 populated states'''
    fig = plt.figure()
    ax_is = fig.add_axes([0, 0, 1, 1])
    #Sorts the states populations
    states = sort_func(states, 2, True)
    #Pulls top 5 state name and population from our sorted state list
    states_name = []
    states_population = []
    for i in range(0, 5):
        states_name.append(states[i][0].strip())
        states_population.append(states[i][2])
    #Displays our graph plot
    ax_is.bar(states_name, states_population[0:5])
    plt.show()
def edit_popul(states, state_name, population):
    '''Updates the population of the requested state'''
    state_found = 0
    index = 0
    for i in range(0, len(states)):
        if state_name[0].strip() == states[i][0].strip().lower():
            state_name = states[i][0]
            state_captital = states[i][1]
            state_flower = states[i][3]
            state_found = 1
            index = i
            break
    if state_found == 1:
        states.pop(index)
        states.insert(index, (state_name, state_captital, int(population[0]), state_flower))
    else:
        print("\nState not found in the list")
#Initializing users input to 1
INPUTENTRY = 1
#Loops until INPUTENTRY is 5
while True:
    #Displays the menu
    print('\n1. View States in ABC Order ')
    print('2. Search for a state ')
    print('3. Top 5 Populated States  ')
    print('4. Edit a State Pop. ')
    print('5. Exit the program ')
    #Collects the users choice
    try:
        INPUTENTRY = int(input('\nEnter choices : '))
    except TypeError:
        # E.g., if b is a string
        print("Invalid option selected\n")
    if INPUTENTRY == 1:
        # Displays information of all U.S. States in Alphabetical order
        display_states_sorted(states)
    elif INPUTENTRY == 2:
        # Search for a state
        state_name = input('Input your State:  ').lower(),
        display_search_of_states(state_name)
    elif INPUTENTRY == 3:
        # Bar graph displaying the top 5 populated states
        highest_5_population(states)
    elif INPUTENTRY == 4:
        # Edit the overall state population for the state requested by user
        state_name = input('Input your State:  ').lower()
        population = input('Input population:  ').lower()
        edit_popul(states, state_name, population)
    elif INPUTENTRY == 5:
        # Exit the program
        sys.exit()
    else:
        print("Invalid option selected\n")


Tags: ofthenameinforifstatepopulation