您好,欢迎来到微智科技网。
搜索
您的当前位置:首页leetcode 1470. 重新排列数组 python一行 解决使用sum()函数时报错unsupported operand type(s) for +: ‘int‘ and ‘tuple‘的问题

leetcode 1470. 重新排列数组 python一行 解决使用sum()函数时报错unsupported operand type(s) for +: ‘int‘ and ‘tuple‘的问题

来源:微智科技网
class Solution:
    def shuffle(self, nums: List[int], n: int) -> List[int]:
        return sum(zip(nums[:n],nums[n:]),())
用zip()函数将列表的前半段和后半段打包,然后用sum()函数拼接。
在用sum()拼接时遇到一个问题,如果直接用
sum(zip(nums[:n],nums[n:])) #去掉第二个参数()
会报错:TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
查阅sum()函数的资料得知
sum(iterable[, start])
参数:
	iterable -- 可迭代对象,如:列表、元组、集合。
	start -- 指定相加的参数,如果没有设置这个值,默认为0。
因为第二个参数默认为0,所以会报错int和tuple不能相加。
而设定第二个参数为()后,即可实现相加,返回一个列表。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 7swz.com 版权所有 赣ICP备2024042798号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务