调用本模块中的示例函数
func
时,为什么会抛出异常
当我使用理解时(可以用参数切换)?有人可以解释一下异常的含义吗? cycle
似乎被覆盖了,我无法理解它。
import pandas as pd
def func(
x_dict,
keys_list,
start_cycle,
end_cycle,
comprehension=True
):
x_test_dicts = {}
for cycle in range(start_cycle, end_cycle + 1):
print(f"cycle = {cycle}")
if comprehension:
# Fill the dict with comprehension.
x_test_dict = {
f"{key}_input":
x_dict[key].query('cycle == @cycle').values
for key in keys_list
}
else:
# Fill the dict with normal for loop.
x_test_dict = {}
for key in keys_list:
x_test_dict[f"{key}_input"] = \
x_dict[key].query('cycle == @cycle').values
x_test_dicts[cycle] = x_test_dict
return x_test_dicts
import pandas as pd
import numpy as np
# Create an ID array from 1 to 1000
ids = np.arange(1, 1001)
# Calculate cycle as ID divided by 100
cycles = ids // 100
# Generate random integer values for the remaining columns
# Assuming a range for random integers (e.g., 0 to 100)
col1_int = np.random.randint(0, 101, 1000)
col2_int = np.random.randint(0, 101, 1000)
col3_int = np.random.randint(0, 101, 1000)
# Update the DataFrame with integer values
df = pd.DataFrame({
"ID": ids,
"cycle": cycles,
"col1": col1_int,
"col2": col2_int,
"col3": col3_int
})
df.head() # Display the first few rows of the updated DataFrame
import pandas as pd
df = df.set_index(['ID', 'cycle']) # Use multi-indexing
x_dict = {'Auxin': df} # Create a simple dict with the DataFrame
keys_list = ['Auxin'] # Define a list of keys to work with
# Define ranges for the loop inside `func`
start_cycle = 6
end_cycle = 29
# RUNS SUCCESSFULLY WITHOUT LIST COMPREHENSION
comprehension = False
result = func(
x_dict,
keys_list,
start_cycle,
end_cycle,
comprehension=comprehension
)
print("Worked without dict comprehension!")
# FAILS WITH LIST COMPREHENSION
comprehension = True
result = func(
x_dict,
keys_list,
start_cycle,
end_cycle,
comprehension=comprehension
)
print("Breaks when dict comprehension is used!")
UndefinedVariableError: local variable 'cycle' is not defined
简而言之,理解的工作原理与人们想象的不同。 他们对下面未公开的局部变量使用不同的作用域。这里有一些阅读:https://peps.python.org/pep-0572/#changing-the-scope-rules-for-compregnions
此处 pandas 和推导式不共享相同的范围,当尝试通过推导式内的 pandas 访问它时,未定义此
cycle
。
一个修复,您可以使用它在 for 循环之前使用
global cycle
以允许访问 cycle
。
第二种方式看起来有点奇怪,但是将循环移到了理解范围。也许在你的真实例子中你可以用更优雅的方式来做到这一点
import pandas as pd
def func(
x_dict,
keys_list,
start_cycle,
end_cycle,
comprehension=True
):
x_test_dicts = {}
for cycle in range(start_cycle, end_cycle + 1):
print(f"cycle = {cycle}")
if comprehension:
# Fill the dict with comprehension.
x_test_dict = {
f"{key}_input":
(cycle := cycle, # defines cycle in the local scope
x_dict[key].query('cycle == @cycle').values)[1] # access element you want
for key in keys_list
}
else:
# Fill the dict with normal for loop.
x_test_dict = {}
for key in keys_list:
x_test_dict[f"{key}_input"] = \
x_dict[key].query('cycle == @cycle').values
x_test_dicts[cycle] = x_test_dict
return x_test_dicts