如何将List1的字符串转为对应List2值的变量?不使用字典实现
Absolutely, this is totally feasible! There are a couple of straightforward ways to map your list items to top-level variables without relying on dict(zip()) or dictionary key lookups. Let's break them down:
Method 1: Modify the namespace with globals() or locals()
Python lets you interact directly with the global or local namespace via the globals() (for global scope) or locals() (for local scope, like inside a function) dictionary. You can dynamically inject variables into this namespace:
List1 = ['a', 'b', 'c'] List2 = [1, 24, 35] # Iterate over paired items and add them to the global namespace for var_name, var_value in zip(List1, List2): globals()[var_name] = var_value # Now you can use the variables directly print(a) # Output: 1 print(b) # Output: 24 print(c) # Output: 35
Key notes for this method:
- If a variable with the same name already exists, it will be overwritten—so double-check for naming conflicts first.
- This only works if
List1contains valid Python variable names (no spaces, special characters, or leading numbers).
Method 2: Use exec() for dynamic assignment
You can also use Python's exec() function to run string-based assignment statements. This is an explicit way to create variables on the fly:
List1 = ['a', 'b', 'c'] List2 = [1, 24, 35] for var_name, var_value in zip(List1, List2): exec(f"{var_name} = {var_value}") # Test the variables print(a) # Output: 1
Key notes for this method:
- Invalid variable names in
List1will throw errors, just like regular Python variable definitions. exec()can be risky with untrusted input, but for your controlled list scenario, it’s completely safe.
A quick word of caution
While these methods do exactly what you want, keep in mind that injecting variables directly into the namespace can make your code harder to read and maintain. Other developers (or future you) might not immediately know where variables like a or b come from. Unless you have a specific use case requiring this approach, a dictionary is often the cleaner, more explicit choice.
内容的提问来源于stack exchange,提问作者Lucas Lemos

