我想在列表列表中搜索和替换值。我拼凑了答案:
我目前的代码有效,但我觉得它需要更复杂。有更优雅的方式吗?
# 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)]
答案 0 :(得分:2)
您已经在使用列表推导,只需将它们组合起来:
replaced_list_of_lists = [
[-1 if e > 5 else e for e in inner_list]
for inner_list in list_of_lists
]
答案 1 :(得分:2)
在嵌套列表解析中的子列表中进行替换,而不必展平和重新组合:
numbers = list(range(10))
list_of_lists = [numbers[i:i+2] for i in range(0, len(numbers), 2)]
# here
list_of_lists = [[-1 if e > 5 else e for e in sublist] for sublist in list_of_lists]