【问题标题】:Methods to search and replace values in nested lists在嵌套列表中搜索和替换值的方法
【发布时间】:2017-01-19 09:06:42
【问题描述】:

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

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

【问题讨论】:

  • 这可能是最 Pythonic 的方式。如果它有效且可读,请不要修复它!
  • @TheLazyScripter 如果它有效且可读,请不要修复它不,在这种情况下不是。

标签: python


【解决方案1】:

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

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]

【讨论】:

    【解决方案2】:

    您已经在使用列表推导,只需将它们组合起来:

    replaced_list_of_lists = [
                [-1 if e > 5 else e for e in inner_list]
                    for inner_list in list_of_lists
            ]
    

    【讨论】:

    • 我不确定这是一个好的答案。列表推导已经大大增加了可读性,将它们组合起来并没有多大帮助。
    • 嗯,这肯定会删除一些代码,所以为什么不呢,但我个人尽量避免大量使用列表理解。
    • @AntoineBolvy 然而,扁平化/替换/重组的原始解决方案只有在您确切知道原始列表的格式时才有效。如果你想要一个通用的解决方案,你需要列表推导或嵌套 for 循环。
    • 是的,当然,尽管不要忘记嵌套列表推导式嵌套for循环的;)
    猜你喜欢
    • 2018-10-15
    • 2016-04-03
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    相关资源
    最近更新 更多