【发布时间】:2017-01-19 09:06:42
【问题描述】:
我想在列表列表中搜索和替换值。我拼凑了以下答案:
我当前的代码有效,但我觉得它比它需要的更复杂。有没有更优雅的方式来做到这一点?
# Create test data- a list of lists which each contain 2 items
numbers = list(range(10))
list_of_lists = [numbers[i:i+2] for i in range(0, len(numbers), 2)]
# Flatten the list of lists
flat_list = [item for sublist in list_of_lists for item in sublist]
# Search for and replace values
modified_list = [-1 if e > 5 else e for e in flat_list]
# Regroup into a list of lists
regrouped_list_of_lists = [modified_list[i:i+2] for i in range(0, len(modified_list), 2)]
【问题讨论】:
-
这可能是最 Pythonic 的方式。如果它有效且可读,请不要修复它!
-
@TheLazyScripter 如果它有效且可读,请不要修复它不,在这种情况下不是。
标签: python