如何将字符串变量转为实际变量?Python参数传递与随机选择问题
Hey there! I see the problem you're facing right now. Your get_word() function is currently returning a random character from the user's input string (like picking 's' from 'sports') instead of a random element from the actual sports or states lists you imported. That's because random.choice([user_input]) is treating the string as an iterable of characters, not referencing the list variable with that name.
Best Approach: Use a Dictionary for Safe Lookup
The cleanest and safest way to map your user's string input to the corresponding list variable is to create a dictionary where the keys are the category strings, and the values are the actual lists. This method is explicit, easy to maintain, and avoids unintended variable access. Here's how to modify your function:
import random import time from sports import sports from states import states def get_word(): # Create a dictionary to link category strings to their respective lists category_map = { 'sports': sports, 'states': states } while True: user_input = input('Select a category (sports or states): ') if user_input in category_map: # Access the correct list using the input string as the dictionary key return random.choice(category_map[user_input]) else: print(f'{user_input} is not a valid category, try again!') print('\n')
Why this works:
- The
category_mapdictionary directly maps user input strings to the imported lists you want to use. If you ever add new categories later, you just need to add another key-value pair to this dictionary. - When the user enters a valid category,
category_map[user_input]pulls the actual list, andrandom.choice()correctly selects a random element from that list instead of the input string.
Alternative (Less Safe): Use globals()
You could technically use the globals() function to access the global variable by its string name, but this is not recommended—it risks accessing unintended global variables if the user enters a string that matches another variable name. Here's what that would look like, just for reference:
def get_word(): while True: user_input = input('Select a category (sports or states): ') if user_input in ['sports', 'states']: # Access the global variable using its string name return random.choice(globals()[user_input]) else: print(f'{user_input} is not a valid category, try again!')
Stick with the dictionary approach—it's more readable and secure for your use case.
That should fix your issue! Now when the user selects "sports" or "states", the function will correctly pick a random element from the corresponding imported list.
内容的提问来源于stack exchange,提问作者Dat Boi

