def get_efficiency_files(folder, keyword): efficiency_files = [] for root, dirs, files in os.walk(folder): for file in files: if keyword in file: match = re.search(r'\d{12}', file) if match: time_str = match.group() time_int = int(time_str) efficiency_files.append({time_int: file}) if not efficiency_files: return None latest_file_dict = max(efficiency_files, key=lambda x: x.keys()) latest_file = latest_file_dict[latest_file_dict.keys()[0]] return latest_file报错信息是“”“dict_keys”对象不可被索引 帮我修改一下
时间: 2024-03-24 12:41:29 浏览: 65
New-folder.rar_This Just In..
好的,因为 `dict.keys()` 返回的是一个类似列表的视图对象,无法直接索引。你可以将 `dict.keys()` 改为 `list(dict.keys())`,即将其转换为列表类型,然后再进行索引。修改后的代码如下:
```python
def get_efficiency_files(folder, keyword):
efficiency_files = []
for root, dirs, files in os.walk(folder):
for file in files:
if keyword in file:
match = re.search(r'\d{12}', file)
if match:
time_str = match.group()
time_int = int(time_str)
efficiency_files.append({time_int: file})
if not efficiency_files:
return None
latest_file_dict = max(efficiency_files, key=lambda x: list(x.keys())[0])
latest_file = latest_file_dict[list(latest_file_dict.keys())[0]]
return latest_file
```
这里的修改只是在 `key` 函数中增加了 `list()` 函数对 `x.keys()` 的转换。
阅读全文