公共方法中的+

108 篇文章 3 订阅

+法运算,都可以用于哪些数据类型之间

int float bool 肯定可以用于加法运算,不再赘述

print(1 + 12.3) # 13.3

str 可以相加么? 可以

str1 = 'hello' str2 = ' python'

字符串相加,可以快速将字符串进行拼接

print(str1 + str2)

相加过后,str1 和str2 没有发生变化,可以推断+法运算产生了新的数据,源数据不变化

print(str1, str2, sep='\n')

list 可以相加么? 可以

list1 = [1, 2, 3] list2 = [4, 5, 6]

列表相加可以将列表进行拼接,效果类似于extend

print(list1 + list2) # [1, 2, 3, 4, 5, 6]

list相加后,原数据不发生变化,将产生一个新的数据

print(list1) # [1, 2, 3] print(list2) # [4, 5, 6]

tuple 可以相加么? 可以

tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) print(tuple1 + tuple2) # (1, 2, 3, 4, 5, 6)

由于元组内部元素不能修改,索引相加肯定没有对源数据产生影响,而是生成了新的数据

set

set1 = {1, 2, 3}

set2 = {4, 5, 6}

# TypeError: unsupported operand type(s) for +: 'set' and 'set'

# set之间不能进行加法运算

print(set1 + set2)

dict

TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

dict 类型间不能进行加法运算

dict1 = {'name': '小明'}

dict2 = {'age':18}

print(dict1 + dict2)

结论: 基础数据类型都可以进行加法运算,容器类型间只有列表,元组,字符串可以进行加法运算

不同容器类型间可以相加么?

list1 = [1,2,3] tuple1 = (1,2,3) set1 = {1,2,3} dict1 = {'name': 'xiaoming'}

TypeError: can only concatenate list (not "tuple") to list

print(list1 + tuple1)

TypeError: can only concatenate list (not "set") to list

print(list1 + set1)

TypeError: can only concatenate tuple (not "set") to tuple

print(tuple1 + set1)

结论,数据类型布偶无法进行加法运算(特指容器类型之间)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值