combinations方法和map函数

1.combinations(iterable,r)方法可以创建一个迭代器,返回iterable中所有长度为r的子序列(好像长度为1时,仍为元组形式)

import itertools

list1=[1,2,3,4]
list2=list(itertools.combinations(list1,2))
print(list2)
print('\n')

list3=[]
for c in itertools.combinations(list1,2):
    list3.append(c)
    print(list3)
print(list3)    
print('\n')

list4=[]
for i in range(1,len(list1)+1):
    c=list(itertools.combinations(list1,i))
    print(c)
    list4.append(c)
print(list4)

[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]


[(1, 2)]
[(1, 2), (1, 3)]
[(1, 2), (1, 3), (1, 4)]
[(1, 2), (1, 3), (1, 4), (2, 3)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]


[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
[(1, 2, 3, 4)]
[[(1,), (2,), (3,), (4,)], [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)], [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)], [(1, 2, 3, 4)]]
>>> 

2.map

x='hello,python'
print(x.split(','))
print(map(eval,x.split(',')))
print(list(map(eval,x.split(','))))
['hello', 'python']
<map object at 0x000002069F494188>
Traceback (most recent call last):
  File "C:/Users/idea/Desktop/4.21.py", line 4, in <module>
    print(list(map(eval,x.split(','))))
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined

若改成数字组成的字符串就可以,因为字符串如果去掉括号就不知道是什么变量了,故hello无法再作为一个变量了
而’1’->1,1还是一个变量,是一个整数

x='1,2,3'
print(x.split(','))
print(map(eval,x.split(',')))
print(list(map(eval,x.split(','))))
['1', '2', '3']
<map object at 0x0000022025694288>
[1, 2, 3]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值