locals()max()min()next()20181011

Python内置函数详解
本文深入解析Python中的内置函数,如locals(), max(), min(), next()等的使用方法和注意事项,通过代码示例展示了如何利用这些函数进行高效编程。

def locals(*args , **kwargs):#real signature unknown
    '''
    Return a dictionary containing the current scope's【范围】 local variables.【当间作用域的局部变量】.

    NOTE:Whether or not updates to this dictionary will affect name lookups【lookup查找】in the local scope and vice-versa【反之亦然】is *implementation dependent* and not covered by and backwards compatibility guarantees.
    '''
    pass

    remark = '''
    locals()查找局部变量名及变量,返回一个字典,在globals()已举例

    '''

    baidu_translate ='''
    
    Return a dictionary containing the current scope's local variables.

    返回包含当前作用域的局部变量的字典。



    NOTE: Whether or not updates to this dictionary will affect name lookups in

    注意:是否更新本词典会影响名称查找

    the local scope and vice-versa is *implementation dependent* and not

    局部范围和反之亦然是*实现依赖*而不是

    covered by any backwards compatibility guarantees

    任何向后兼容性保证'''


    baidu_words = '''
    dictionary词典,字典; 代码字典
    containing包含; 控制( contain的现在分词 ); 克制; 牵制
    scope范围; 眼界,见识; 余地; 广袤,地域; 审视,仔细研究
    local variables区域变数.   :局部变量
    Whether or not是否; 无论
    vice-versa反之亦然
    dependent依赖的; 依靠的; 取决于…的; 有瘾的; 受抚养人; 受赡养者; 依赖他人者; 扈从,侍从
    backwards向后的; 倒行的; 返回的; 落后的; 向后; 倒; 往后; 逆
    compatibility适合; 互换性; 通用性; 和睦相处
    guarantees担保( guarantee的名词复数 ); 担保品; 保修单; 抵押品
        '''

def max(*args , **kwargs):#known special case of max【已知的特定实例最大值】
    '''
    max(iterable , *[,default=obj,key=func]) ---> value
    max(arg1,arg2,*args,*[,key=func]) ---> value

    With a single iterable argument ,return its biggest item.The default keyword-only argument specifes and object to return if the provided iterable is empty.
    With two or more arguments,return the largest argument.
    '''
    pass

    remark = '''
    求最大值
    max(arg1, arg2, *args, *[, key=func])这个形式的含义为:
        arg1,arg2是必传的,也就是至少两个参数
        *args代表可以传入多个参数,以元祖的形式传入
        *[,key=func]。把[]去掉就是,key=func。[]里面可有可无
        举例:
            max(arg1,arg2,arg3 , key=func) ---> 本质:max(arg1,arg2,(arg3,) , key=func):arg3后面的逗号代表是元祖
    '''



    baidu_translate = '''
    max(iterable, *[, default=obj, key=func]) -> value

        max(迭代,*[默认= Obj',key=Func])->值

    max(arg1, arg2, *args, *[, key=func]) -> value

        MAX(ARG1,ARG2,*ARGS,*[,密钥= FUNC])->值

    With a single iterable argument, return its biggest item. The

        使用一个可重复的参数,返回其最大项。这个

    default keyword-only argument specifies an object to return if

        默认关键字仅参数指定要返回的对象

    the provided iterable is empty.

        所提供的迭代是空的。

    With two or more arguments, return the largest argument.

        使用两个或更多个参数,返回最大的参数。
    '''


    baidu_words = '''
    default未履行任务或责任; 受传唤时未出庭; 由于不到庭而败诉; 弃权; 未履行,拖欠; 未参加或完成; 因未到庭而败; 未到庭; 
            缺省,默认
    obj目标; object 物体; 项目; objection 反对
    func功能; 作用; function 官能; 职责
    argsanti-radar guidance sensor 防雷达跟踪传感器
    argument论据; 争论,争吵; 幅角; 主题,情节
    biggest大的,长大的; 大的( big的最高级 ); 重要的; 庞大的; 大方的
    specifies指定( specify的第三人称单数 ); 详述; 提出…的条件; 使具有特性
    object to反对, 对…反感; 非; 不以为然
    empty空的,空虚的,空洞的; 空闲的,无效的,徒劳的; 无聊的,愚蠢的; 言语或行动空洞的; 成为空的, 把…弄空; 把…腾出来; 成为空的; 流空; 空车; 空的东西
    arguments论据; 争吵; 争论( argument的名词复数 ); 说理

    '''

    #代码,验证
    '和下面的min()一起'








求最小值函数min()--->https://www.cnblogs.com/whatisfantasy/p/6273913.html

def min(*args , key=None):#known special case of min
    '''
    min(iterable , *[,default=obj,key=func]) ---> value
    min(arg1 , arg2 , *args,*[,key=func]) ---> value

    With a single iterable argument ,return its smallest item.The default keyword-only argument specifies an object to return if the provided iterable is empty.
    With two or more arguments,return the smallest argument.
    '''
    pass
    remark = '''
    求最小值,当提供的可迭代的对象为空时,返回一个指定的对象
    '''



    baidu_translate = '''
    min(iterable, *[, default=obj, key=func]) -> value

        min(迭代,*[缺省值= OBJ,KEY=FUNC])->值

    min(arg1, arg2, *args, *[, key=func]) -> value

        min(ARG1,ARG2,*ARGS,*[,密钥= FUNC])->值


    With a single iterable argument, return its smallest item. The

        使用一个可重复的参数,返回其最小项。这个

    default keyword-only argument specifies an object to return if

        默认关键字仅参数指定要返回的对象

    the provided iterable is empty.

        所提供的迭代是空的。

    With two or more arguments, return the smallest argument.

        使用两个或多个参数,返回最小的参数。
    '''


    baidu_words = '''
    minminute 分; minuto (Portuguese or Spanish=minute) 分; minority 少数; miniature 小型的
    default未履行任务或责任; 受传唤时未出庭; 由于不到庭而败诉; 弃权; 未履行,拖欠; 未参加或完成; 因未到庭而败; 未到庭; 缺省,默认
    obj目标; object 物体; 项目; objection 反对
    func功能; 作用; function 官能; 职责
    argsanti-radar guidance sensor 防雷达跟踪传感器
    argument论据; 争论,争吵; 幅角; 主题,情节
    smallest小的( small的最高级 ); 小气的; 小号的; 小规模的
    specifies指定( specify的第三人称单数 ); 详述; 提出…的条件; 使具有特性
    object to反对, 对…反感; 非; 不以为然
    arguments论据; 争吵; 争论( argument的名词复数 ); 说理
    '''

    #代码,验证

>>> products = {"买房1":350,"买车2":20,"娶老婆":50,"生孩子":30,"小孩教育":10}
>>> max(products)#直接传字典,集合默认用key排序的
'生孩子'

>>> key = list(products.keys())
>>> key
['买房1', '买车2', '娶老婆', '生孩子', '小孩教育']
>>> max(key)
'生孩子'


>>> min(products)
'买房1'
>>> min(key)
'买房1'


>>> max(products, key=lambda x:products[x])#指定按value排序,products[key] = value
'买房1'#打印最大值项目的key

>>> value = list(  products.values()  )
>>> value
[350, 20, 50, 30, 10]
>>> max(value)
350#打印最大值项目的value
#怎么样把最大值,最小值的key,value都弄出来?  zip()
#参数为字典|集合时 按key排序


>>> min(products, key=lambda x:products[x])
'小孩教育'


>>> max(zip(products.keys() , products.values() ))
('生孩子', 30)
>>> max(zip(products.values() , products.keys() ))#把products的key,value,zip成了value,key
(350, '买房1')
>>> min(zip(products.values() , products.keys() ))
(10, '小孩教育')
>>> min_zip_turn = min(zip(products.values() , products.keys() ))
>>> min_zip_turn
(10, '小孩教育')
>>> goal = {min_zip_turn[1]:min_zip_turn[0]}
>>> goal
{'小孩教育': 10}

#下面是想看看zip()
>>> z = zip(  products.values() , products.keys()  )
>>> z
<zip object at 0x1021e7348>
>>> list(z)
[(350, '买房1'), (20, '买车2'), (50, '娶老婆'), (30, '生孩子'), (10, '小孩教育')]
>>> tuple(z)#这下成空的了,关于zip的知识点,后面再深究
()
>>> z
<zip object at 0x1021e7348>
>>> list(z)
[]
>>> z = zip(  products.values() , products.keys()  )#重新zip一下
>>> tuple(z)
((350, '买房1'), (20, '买车2'), (50, '娶老婆'), (30, '生孩子'), (10, '小孩教育'))
>>> z = zip(  products.values() , products.keys()  )
>>> set(z)
{(350, '买房1'), (20, '买车2'), (50, '娶老婆'), (30, '生孩子'), (10, '小孩教育')}
>>> z = zip(  products.values() , products.keys()  )
>>> dict(z)
{350: '买房1', 20: '买车2', 50: '娶老婆', 30: '生孩子', 10: '小孩教育'}
>>> max( dict(zip(  products.values() , products.keys()  )) )
350
>>> max(zip(  products.values() , products.keys()  ))
(350, '买房1')
>>> 

#排大小,max,min会有自己的规则
>>> max(chr(65) , chr(66) , chr(100))
'd'#chr(100)
>>> chr(65)
'A'
>>> chr(66)
'B'
>>> chr(100)
'd'
>>> max("小米1","小米5","小米8")#8在ASCII码里比1,5后。所以大
'小米8'
>>> max("小米1","小米11","小米111")#
'小米111'
>>> max("小米1000","小米11","小米111")
'小米111'
>>> max("爱小米1","小米11","小米111")#这是什么规律呢
'爱小米1'
>>> 








next()生成迭代器里下一个元素

def next(iterator , default=None):#real signature unknown;restored from __doc__
    '''
    next(iterator[,default])
    
    Return the next item from the iterator.
    If default is given and the iterator is exhausted【用尽的】,it is returned instead of raising StopIteration.
    '''
    pass

    remark = '''
    从迭代器获取并返回下一个项目,如果项目用完了就抛出StopIteration异常,for 循环不会抛出。
    如果给了默认值,并且默认值在迭代器里会把默认值直接抛出,就算迭代器就算用完了,也不会抛出异常(详见验证)。
    格式:next(iterator[,default])。比如next(iter([1,2,3]) ,2).不是next(iter([1,2,3]) ,default=2)
    '''

    baidu_translate_set = '''
    next(iterator[, default])

        下一步(迭代器[默认])

    Return the next item from the iterator.

        从迭代器返回下一个项目。

    If default is given and the iterator is exhausted,

        如果给定默认值以及迭代器已用完,

    it is returned instead of raising StopIteration.

        它返回这个默认值,而不是抛出异常说:停止迭代。
    '''

    baidu_words = '''
    next紧接在后的; 次于的; 贴近的; 紧邻的; 接下去; 然后; 居后地; 依次的; 下一个; 下一位; 靠近; 居于…之后; 在…的隔壁
    iterator迭代器,迭代程序
    default未履行任务或责任; 受传唤时未出庭; 由于不到庭而败诉; 弃权; 未履行,拖欠; 未参加或完成; 因未到庭而败; 未到庭; 
            缺省,默认
    item项目; 条,条款; 一则; 一件商品; 又,同上
    given指定的,确定的; 假设的,假定的; 有…倾向的; 赠送的; 考虑到; 倘若,假定; 假设; 给予,赠送( give的过去分词)
    exhausted精疲力竭的; 筋疲力尽的; 耗尽的; 用完的; 用尽( exhaust的过去式和过去分词 ); 使非常疲倦; 详尽讨论; 弄空
    returned被送回的,归来的; 恢复; 归还; 返回,回来( return的过去式和过去分词 ); 还
    instead of代替…, 而不是…, 而不用…
    raising提高; 增加; 高岗; 高地; 养育; 引起( raise的现在分词 ); 提起; 唤起

    '''



    #代码验证
>>> iter_l = iter([1,2,3])
>>> next(iter_l)
1
>>> next(iter_l)
2
>>> next(iter_l)
3
>>> next(iter_l)#next()取完了就报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

>>> next(iter_l , default=2)#不是这种语法形式
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: next() takes no keyword arguments

>>> next(iter_l , 2)
2
>>> next(iter_l , 2)
2

>>> next(iter_l , 3)
3
>>> next(iter_l , 4)#没有4也返回4 , 并且类型是int。这样目前觉得没有意义,不知道设计者的角度是什么
4
>>> next(iter_l , 5)
5
>>> a = next(iter_l , 5)
>>> a
5
>>> type(a)
<class 'int'>
>>> 


转载于:https://www.cnblogs.com/wujianghu/p/9772518.html

原始损伤数据形状: (2000,), 前3个值: [0. 0. 0.] 优化后损伤数据形状: (2000,), 前3个值: [0. 0. 0.] 时间序列长度: 2000, 前3个时间点: [1 2 3] 初始化坐标轴范围: x=[(0.0, 1999.0)], y=[(0.0, 0.884065656302249)] 初始化坐标轴范围: x=[(0.0, 1999.0)], y=[(0.0, 0.884065656302249)] 初始化坐标轴范围: x=[(0.0, 1999.0)], y=[(0.0, 0.884065656302249)] Traceback (most recent call last): File D:\anaconda3\Lib\site-packages\matplotlib\animation.py:223 in saving yield self File D:\anaconda3\Lib\site-packages\matplotlib\animation.py:1085 in save anim._draw_next_frame(d, blit=False) File D:\anaconda3\Lib\site-packages\matplotlib\animation.py:1120 in _draw_next_frame self._draw_frame(framedata) File D:\anaconda3\Lib\site-packages\matplotlib\animation.py:1746 in _draw_frame self._drawn_artists = self._func(framedata, *self._args) File c:\users\1\desktop\未命名1.py:110 in update print(f"第{frame}帧数据范围: x=[0-{frame}], y=[{min(original_damage[:frame])}-{max(original_damage[:frame])}]") ValueError: min() iterable argument is empty During handling of the above exception, another exception occurred: Traceback (most recent call last): File D:\anaconda3\Lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec exec(code, globals, locals) File c:\users\1\desktop\未命名1.py:145 ani.save('damage_comparison.gif', writer='pillow', fps=10) File D:\anaconda3\Lib\site-packages\matplotlib\animation.py:1069 in save with writer.saving(self._fig, filename, dpi), \ File D:\anaconda3\Lib\contextlib.py:158 in __exit__ self.gen.throw(value) File D:\anaconda3\Lib\site-packages\matplotlib\animation.py:225 in saving self.finish() File D:\anaconda3\Lib\site-packages\matplotlib\animation.py:495 in finish self._frames[0].save( IndexError: list index out of range
最新发布
07-17
<think>好的,用户提供的代码在运行时出现了错误,主要问题是原始损伤数据和优化后的损伤数据的前三个值都是0,导致在生成动画时出现ValueError和IndexError。我需要仔细分析代码,找出问题所在并提出解决方案。 首先,用户提到原始损伤数据和优化后的数据前三个值都是0,这可能意味着数据加载或处理过程中存在问题。检查`load_and_align_damage_data`函数,发现该函数读取Excel文件中的'MainShaft'和'Tower'工作表,但用户的数据文件可能没有正确包含这些工作表,或者列数不足,导致插值后的数据全为0。此外,在`optimize_active_power`函数中,如果线性规划求解失败,会默认返回满发功率,但此时损伤权重可能没有正确计算,导致结果异常。 其次,在动画创建时,当所有数据都是0时,`max(original_damage)`和`max(optimized_damage)`的结果也为0,导致坐标轴范围设置为0到0*1.1=0,这会导致绘图区域无法显示任何内容。此外,在`update`函数中,当frame为0时,original_damage[:0]是空列表,调用minmax会抛出错误。 解决步骤包括: 1. 验证数据加载是否正确,确保Excel文件中的工作表和列正确无误。 2. 在计算坐标轴范围时,添加对全零数据的处理,避免除以零或无效范围。 3. 在`update`函数中处理frame=0的情况,避免空列表导致的错误。 4. 确保线性规划的约束条件正确,避免求解失败导致默认值影响结果。 最后,建议用户检查输入文件的数据格式和内容,确保数据正确性,并在代码中添加更多的错误处理和调试信息,以便快速定位问题。 </think>```python # 修复后的完整代码(重点修复数据处理和动画初始化逻辑) import pandas as pd import numpy as np from scipy.optimize import linprog from scipy.interpolate import interp1d import matplotlib.pyplot as plt import matplotlib.animation as animation # 加载功率和风速数据(无表头+整数时间序列) def load_power_and_wind_data(file_path): df = pd.read_excel(file_path, header=None) if df.shape[1] < 3: raise ValueError("输入文件至少需要3列数据(时间/调度指令/风速)") time = df.iloc[:, 0].astype(int) power_dispatch = df.iloc[:, 1] wind_speed = df.iloc[:, 2] time_diff = 1 # 假设时间间隔为1秒 n_turbines = len(power_dispatch) // 2000 remainder = len(power_dispatch) % 2000 if remainder != 0: print(f"警告:文件行数{len(power_dispatch)}不能被2000整除,余{remainder}行将被忽略") turbine_data = [] for i in range(n_turbines): start_idx = i * 2000 end_idx = start_idx + 2000 turbine_data.append({ 'time': time[start_idx:end_idx], 'power': power_dispatch[start_idx:end_idx], 'wind': wind_speed[start_idx:end_idx] }) return turbine_data, n_turbines, time_diff # 加载并对齐损伤数据(无表头+整数时间) def load_and_align_damage_data(damage_file, n_turbines, target_time): try: main_damage_df = pd.read_excel(damage_file, sheet_name='MainShaft', header=None, skiprows=1) tower_damage_df = pd.read_excel(damage_file, sheet_name='Tower', header=None, skiprows=1) except Exception as e: print(f"读取Excel文件失败: {e}") return np.zeros((len(target_time), n_turbines)), np.zeros((len(target_time), n_turbines)) source_time = main_damage_df.iloc[:, 0].astype(int) aligned_main = [] aligned_tower = [] for i in range(n_turbines): try: source_main = main_damage_df.iloc[:, i+1].values source_tower = tower_damage_df.iloc[:, i+1].values f_main = interp1d(source_time, source_main, kind='linear', fill_value='extrapolate') f_tower = interp1d(source_time, source_tower, kind='linear', fill_value='extrapolate') aligned_main.append(f_main(target_time)) aligned_tower.append(f_tower(target_time)) except Exception as e: print(f"第{i}台风机插值失败: {e}") aligned_main.append(np.zeros(len(target_time))) aligned_tower.append(np.zeros(len(target_time))) return np.array(aligned_main).T, np.array(aligned_tower).T # 优化有功功率分配 def optimize_active_power(turbine_data, main_damage, tower_damage): n_points = len(turbine_data[0]['time']) optimal_power = [] for i in range(n_points): total_power = turbine_data[0]['power'][i] if total_power <= 0: optimal_power.append([0]*len(turbine_data)) continue A_eq = np.array([[1]*len(turbine_data)]) b_eq = np.array([total_power]) bounds = [(0, 2000) for _ in turbine_data] damage_weights = main_damage[i] + tower_damage[i] result = linprog(damage_weights, A_eq=A_eq, b_eq=b_eq, bounds=bounds) if result.success and np.sum(result.x) > 0: optimal_power.append(result.x) else: # 按等比例分配替代默认满发 optimal_power.append([total_power/len(turbine_data)]*len(turbine_data)) return np.array(optimal_power) # 创建动态可视化 def create_animation(original_damage, optimized_damage, time_data): fig, ax = plt.subplots(figsize=(12, 6)) x = np.arange(len(time_data)) line1, = ax.plot([], [], label='Original Damage', color='red', lw=2) line2, = ax.plot([], [], label='Optimized Damage', color='blue', lw=2) time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes, fontsize=12, bbox=dict(facecolor='white', alpha=0.8)) ax.set_xlabel('Time Step', fontsize=10) ax.set_ylabel('Cumulative Damage', fontsize=10) ax.tick_params(axis='both', labelsize=8) ax.grid(True, linestyle='--', alpha=0.7) ax.legend(fontsize=8) def init(): non_zero = original_damage > 1e-9 if np.any(non_zero): max_val = max(max(original_damage), max(optimized_damage)) y_range = max_val * 1.2 else: y_range = 1.0 ax.set_xlim(0, len(time_data)-1) ax.set_ylim(0, y_range) return line1, line2, time_text def update(frame): if frame == 0: line1.set_data([], []) line2.set_data([], []) time_text.set_text('') return line1, line2, time_text valid = original_damage[:frame] > 1e-9 if np.any(valid): y_min = min(original_damage[:frame][valid]) y_max = max(original_damage[:frame][valid]) else: y_min, y_max = 0, 1.0 ax.set_ylim(y_min - 0.1, y_max * 1.2) line1.set_data(x[:frame], original_damage[:frame]) line2.set_data(x[:frame], optimized_damage[:frame]) time_text.set_text(f'Processing: Step {time_data[frame]}') return line1, line2, time_text ani = animation.FuncAnimation(fig, update, frames=len(time_data), init_func=init, blit=True, interval=20) return ani # 主程序 if __name__ == "__main__": power_wind_file = 'output_data.xlsx' damage_file = '附件5-问题一答案表.xlsx' # 1. 加载调度指令和风速数据 turbine_data, n_turbines, time_interval = load_power_and_wind_data(power_wind_file) # 2. 加载并对齐损伤数据 target_time = turbine_data[0]['time'].values main_damage, tower_damage = load_and_align_damage_data(damage_file, n_turbines, target_time) # 3. 执行优化计算 optimal_power = optimize_active_power(turbine_data, main_damage, tower_damage) # 4. 计算损伤累积(示例逻辑) original_damage = np.sum(main_damage + tower_damage, axis=1) optimized_damage = np.sum((main_damage + tower_damage) * optimal_power/2000, axis=1) # 5. 添加数据验证 print(f"原始损伤数据形状: {original_damage.shape}, 前3个值: {original_damage[:3]}") print(f"优化后损伤数据形状: {optimized_damage.shape}, 前3个值: {optimized_damage[:3]}") print(f"时间序列长度: {len(target_time)}, 前3个时间点: {target_time[:3]}") # 6. 创建动画 ani = create_animation(original_damage, optimized_damage, target_time) # 7. 保存动画文件(离线模式) try: ani.save('damage_comparison.gif', writer='pillow', fps=10) plt.close() print("动画已成功保存为 damage_comparison.gif") except Exception as e: print(f"保存动画失败: {e}") plt.show() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值