簡體   English   中英

遞歸對嵌套列表中的所有元素進行平方

[英]recursion to square all elements in nested lists

我在期中沒能回答這個問題。 我不是要你們幫我做作業。 只是想知道如何解決這個問題。 我只知道如何使用列表索引來解決這個問題,但是這里不允許這個解決方案,因為問題已經說明我必須在函數中包含“for x in nums”。 我知道 int 是不可變的,那我該怎么辦? 感謝“isinstance”的提示,但很抱歉我們之前沒有學過,所以我不能在考試中使用它。

我剛剛學會了如何使用索引解決類似的問題。 我認為它可以像這樣工作:

def square_all(nums):
    new = []
    for x in nums:
        new.append(x)
    for i in range(len(new)):
        if type(new[i]) != list:
            new[i] = new[i] ** 2
        else:
            square_all(new[i])
    return new

它不能很好地工作。 我認為“其他”有問題。 但是我該怎么修改呢?

編寫一個 python 函數square_all ,它接受一個參數,一個整數嵌套列表,並返回一個新的整數嵌套列表,該列表在結構上與給定列表相同,但其中所有整數都已平方。 請注意,該函數不應修改其參數; 它應該建立一個新的、單獨的列表。

通過在循環的上方、內部或下方編寫您認為需要的任何內容來完成該功能。 不要在函數之外編寫代碼。 假設您沒有可用的全局變量。 不要更改已提供的代碼。

例子:

 square_all([1,2,[3,4]]) = [1,4,[9,16]]

給定代碼:

 def square_all(nums;'nested list of integers') -> 'nested list of integers': for x in nums:

這是這個問題的一個非常通用的解決方案:

def map_nested(fnc, obj):
    if isinstance(l, (list, set, tuple)):  # whatever collection type you want
        return type(obj)(map_nested(fnc, sub) for sub in obj)
    return fnc(obj)        

> map_nested(lambda x: x**2, [1, 2, (3, 4, set([5, 6]))])
[1, 4, (9, 16, set([25, 36]))]

您可以將遞歸函數創建為:

def get_square(l):
    return [get_square(e) if isinstance(e, list) else e**2 for e in l]
    #                           ^ to check object is of `list` type

示例運行:

>>> get_square([1,2,[3,4]])
[1, 4, [9, 16]]

但是,此函數僅支持list作為嵌套對象。 如果您將元組作為嵌套結構傳遞,它將失敗。 例如:

>>> get_square([1,2,(3,4)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in get_square
TypeError: unsupported operand type(s) for ** or pow(): 'tuple' and 'int'

如果您希望您的函數支持所有可迭代對象,您應該對collections.Iterable進行isinstance檢查。 因此你的功能應該是這樣的:

from collections import Iterable

def get_square(l):
    return type(l)(get_square(e) if isinstance(e, Iterable) else e**2 for e in l)
    #        ^                        ^ check for `collections.Iterable`
    #        ^ for preserving the type of `Iterables`

示例運行:

>>> get_square([1,2,(3,4)])
[1, 4, (9, 16)]

您的代碼的問題在於您創建了一個列表,因此僅調用square_all(new[i])不會更改new[i] 您必須分配結果: new[i] = square_all(new[i])

def square_all(nums):
    new = []
    for x in nums:
        new.append(x)
    for i in range(len(new)):
        if type(new[i]) != list:
            new[i] = new[i] ** 2
        else:
            new[i] = square_all(new[i])  # assign result to new[i]
    return new

或者更短一點,直接附加最終值,而不是先使用原始值,然后再覆蓋它們:

def square_all(nums):
    result = []
    for n in nums:
        if type(n) is list:
            result.append(square_all(n))
        else:
            result.append(n**2)
    return result

或者非常簡短,在列表理解中使用給定的代碼:

def square_all(nums):
    return [square_all(n) if type(n) is list else n**2 for n in nums]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM