gpt4 book ai didi

python - 在嵌套列表中搜索和替换值的方法

转载 作者:太空宇宙 更新时间:2023-11-04 10:08:57 24 4
gpt4 key购买 nike

我想搜索和替换列表列表中的值。我拼凑了以下问题的答案:

  1. Flatten a nested list
  2. Search for and replace a value
  3. Regroup the flat list into a list of lists

我当前的代码有效,但我觉得它比需要的更复杂。有更优雅的方法吗?

# 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)]

最佳答案

嵌套列表理解中进行子列表的替换,而无需展平和重新组合:

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]

关于python - 在嵌套列表中搜索和替换值的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39441646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com