【问题标题】:Can I flatten an array without making a new list/array? [duplicate]我可以在不创建新列表/数组的情况下展平数组吗? [复制]
【发布时间】:2021-02-24 12:39:52
【问题描述】:

假设我有arr = [[1], [0, 0], [2], [3], [0, 0], [4]]

我是否可以将其扁平化为 [1, 0, 0, 2, 3, 0, 0, 4] 而无需使用 itertools、map/reduce 或列表组合?我正在努力寻找一种方法来做到这一点。谢谢。

这是我到目前为止尝试过的,这是一个 leetcode 问题:https://leetcode.com/problems/duplicate-zeros/

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        
        """
        for ix in range(len(arr) - 2):
            if arr[ix] == 0:
                arr[ix] = [0, 0]
                del arr[-1]
            else:
                l = []
                l.append(arr[ix])
                arr[ix] = l

# Output when you return arr is [[1],[0, 0],[2],[3],[0, 0],[4]]

【问题讨论】:

  • 你为什么不想使用列表推导?这似乎是扁平化列表的最佳解决方案。
  • “无需使用 itertools、map/reduce 或 list comp”——这似乎很随意。为什么要排除这些工具?如果您知道其他可以使嵌套列表变平的方法,您是否也会排除这种情况?
  • 到目前为止你有什么尝试?
  • 您能指出为什么您不想使用列表推导、itertools 等吗?理解允许非常简单和 Pythonic 的解决方案:[x for items in arr for x in items]
  • 任意排除使用的东西[检查] - 还没有代码[检查] - 作业?

标签: python arrays list flatten


【解决方案1】:

你可以这样做:

arr = sum(arr, [])

您在这里所做的是添加 arr 的可迭代元素,将空数组 [] 作为初始值。

【讨论】:

  • 这是非常低效的 - 它是二次时间。
  • @user2357112supportsMonica 我同意,我不争论这个。我的只是另一种可能的解决方案,当我发布时符合问题要求(不要使用列表理解、映射、减少,不要创建新列表)。正如您所看到的,问题要求非常严格,而且我注意到它们也在发生变化,它已经被编辑了好几次。也许这不是最好的解决方案,它是一个可能的解决方案。如果有更好的我也很乐意学习
【解决方案2】:
  • 我们也可以在这里使用list copy ([:]) 来解决问题:
class Solution:
    def duplicateZeros(self, A):
        """
        Do not return anything, modify arr in-place instead.
        """
        A[:] = [x for num in A for x in ([num] if num else [0, 0])][:len(A)]
  • 此外,最佳解决方案是具有恒定内存的 N 级运行时。 LeetCode here 已经解决了这个问题:
class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """

        possible_dups = 0
        length_ = len(arr) - 1

        # Find the number of zeros to be duplicated
        for left in range(length_ + 1):

            # Stop when left points beyond the last element in the original list
            # which would be part of the modified list
            if left > length_ - possible_dups:
                break

            # Count the zeros
            if arr[left] == 0:
                # Edge case: This zero can't be duplicated. We have no more space,
                # as left is pointing to the last element which could be included  
                if left == length_ - possible_dups:
                    arr[length_] = 0 # For this zero we just copy it without duplication.
                    length_ -= 1
                    break
                possible_dups += 1

        # Start backwards from the last element which would be part of new list.
        last = length_ - possible_dups

        # Copy zero twice, and non zero once.
        for i in range(last, -1, -1):
            if arr[i] == 0:
                arr[i + possible_dups] = 0
                possible_dups -= 1
                arr[i + possible_dups] = 0
            else:
                arr[i + possible_dups] = arr[i]

【讨论】:

    【解决方案3】:

    尝试一些递归:

    def flatten(lst):
        ans = []
        for el in lst:
            if type(el) == list:
                 for e in flatten(el):
                     ans.append(e)
            else:
                ans.append(el)
        return ans
    

    它将展平任何维度的列表。

    【讨论】:

      猜你喜欢
      • 2012-12-24
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 2016-02-24
      • 2010-11-29
      • 2010-11-25
      • 2013-06-11
      相关资源
      最近更新 更多