【问题标题】:how can I make the original list passed though the function and modified, but don't return a new list instead add on to old list?如何使原始列表通过函数并进行修改,但不返回新列表而是添加到旧列表中?
【发布时间】:2022-01-23 01:18:08
【问题描述】:

list 输出 4, 16, 36 但应该输出 2, 4, 6, 4, 16, 36 如果我采用旧数字和 **2 的话,我的原始数字和新数字的组合列表。

def squareEach(nums):
    
    for i in range(len(nums)):
        
        nums [i] = nums[i]**2

def test ():
    
    nums = [2,4,6]
    
    squareEach(nums)
    
    print("List:", nums)

test()   

【问题讨论】:

    标签: python list function


    【解决方案1】:

    您需要将appendextend 发送至列表。

    >>> def append_squares(nums):
    ...     nums.extend([n ** 2 for n in nums])
    ...
    >>> nums = [2, 4, 6]
    >>> append_squares(nums)
    >>> nums
    [2, 4, 6, 4, 16, 36]
    

    【讨论】:

    • 谢谢您,您的评论非常有帮助,我在发布问题之前尝试了追加,但我现在看到我实施错误,但扩展从未想过。你是男人
    【解决方案2】:

    nums.append(nums[i]**2)代替nums[i] = nums[i]**2

    【讨论】:

    • 谢谢,您的评论非常有帮助,而且答案很明确。
    猜你喜欢
    • 1970-01-01
    • 2017-05-23
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多