python :unpacking elements

>>> tuple1 =(2,4)
>>> x,y = tuple1
>>> tuple1[0]
2
>>> x
2
>>> y
4
>>> type(tuple1)
<class 'tuple'>
>>> list1 =['apple',10.3,3,"High quality",["green","USA",3]]
>>> catelog,price,quantity,comment,info = list1
>>> catelog
'apple'
>>> price
10.3
>>> quantity
3
>>> comment
'High quality'
>>> info
['green', 'USA', 3]
>>> type(list1)
<class 'list'>
>>> 
>>> 
>>> title = "Hello"
>>> a,b,c,d,e = title
>>> a
'H'
>>> b
'e'
>>> c
'l'
>>> d
'l'
>>> e
'o'
>>> type(title)
<class 'str'>
>>> 
>>> 
>>> a,b = title
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    a,b = title
ValueError: too many values to unpack (expected 2)
>>> a,*b = title
>>> a
'H'
>>> b
['e', 'l', 'l', 'o']

>>> 

>>> record =("Dave",'dave@example.com','9999999','8878877','man')
>>> name , email,*tel,sex = record
>>> name
'Dave'
>>> email
'dave@example.com'
>>> tel
['9999999', '8878877']
>>> sex

'man'

>>> records =[("foo",1,2),("bar","hello"),("foo",3,4)]
>>> for tag ,*contents in records:
print(tag,contents)



foo [1, 2]
bar ['hello']
foo [3, 4]
>>> for tag ,*contents in records:
if(tag=="foo"):
print(tag,contents[0],contents[1])
else :
print(tag,contents)



foo 1 2
bar ['hello']
foo 3 4
>>> def do_foo(x,y)
SyntaxError: invalid syntax
>>> def do_foo(x,y):
print('foo',x,y)



>>> def do_bar(s):
print("bar',s)
      
SyntaxError: EOL while scanning string literal
>>> def do_bar(s):
print("bar",s)


      
>>> for tag ,*contents in records:
if(tag=="foo"):
do_foo(*contents)
else :
do_bar(*contents)


      
foo 1 2
bar hello
foo 3 4
>>> for tag ,*contents in records:
if(tag=="foo"):
do_foo(contents)
else :
do_bar(contents)


      
Traceback (most recent call last):
  File "<pyshell#67>", line 3, in <module>
    do_foo(contents)
TypeError: do_foo() missing 1 required positional argument: 'y'
>>> 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值