python-元组

来源:互联网 发布:网络回路检测 编辑:程序博客网 时间:2024/06/06 09:57


##########################元组###################################
###1
,元组的定义

1
)定义空元组
tuple = ()

2)
定义单个值的元组
tuple = (fentiao,)

3)
一般的元组
tuple = (fentiao
8male)

###
字符中操作提取姓名/年龄/性别的方式不方便,诞生元组与列表这两个数据类型
>>> t1 = ("fentiao",4,"male")
>>> t2 = ("westos",10,"unknown")
>>> type(t1)
<type 'tuple'>
>>> type(t2)
<type 'tuple'>
>>> t1[0]
'fentiao'
>>> t2[0]
'westos'
>>> t2[0:2]
('westos', 10)
>>> t1
('fentiao', 4, 'male')
>>> ti[1] = 5  ------>
不能对元组的值任意更改
Traceback (most recent call last):
 
File "<stdin>", line 1,in <module>
NameError: name 'ti' is not defined
>>> t1
('fentiao', 4, 'male')
>>> a,b,c=(1,2,3)
>>> print a,b,c
1 2 3
>>> name,age,gender = t1  ----->
对元组分别赋值,引申对多个变量也可通过元组方式赋值
>>> print name,age,gender
fentiao 4 male


具体示例:

1.
输入一个英文句子,统计该英文句子中含有单词的数目
提示:英文单词间可以认为都用英文空格集进行分割。
测试数据:
   -
输入:I likepython very much
   -
输出
:5
str = raw_input('English sentence:')
str1 = str.split()
print len(str1)


2.
输入一个字符串,并进行判断是否正确
str = raw_input("string:")
if str[0] not in string.letters + '_':
   print '
第一个位置不符合'
   
exit(0)
else:
   
for i in str[1:]:
       
if i not instring.letters+string.digits+'_':
            print 'i
位不合法'
            
exit(0)
print '
此输入合法'

原创粉丝点击