在python语言中、+表示_如何用python语言表示一个序列

>>> numbers = [15, -2, 3, 42, 102]

>>> max(numbers)

102

>>> min(numbers)

-2

>>> max('Python')

'y'

>>> min('Python')

'P'

2. in和not in

使用in和not in操作符来判断某个子序列是否在该序列中:

>>> 1 in [1, 2, 3]

True

>>> 4 not in [1, 2, 3]

True

>>> 'p' in 'Python'  # Python区分大小写

False

>>> 'yth' in 'Python'  # 不仅仅可以判断单个字符

True

3. “+”和“*”

使用“+”操作符来拼接序列,使用“*”操作符来重复相加序列:

>>> 'Py' + 'thon'

'Python'

>>> 'I love you!' * 5

'I love you!I love you!I love you!I love you!I love you!'

列表的“+”操作与extend()方法类似,但是“+”操作不是就地操作,有返回值:

>>> list1 = [1, 2, 3]

>>> list2 = [4, 5, 6]

>>> list3 = list1 + list2

>>> list3

[1, 2, 3, 4, 5, 6]

>>> list4 = list1.extend(list2)

>>> list4  # list4是None

>>> list1  # list2追加到了list1上

[1, 2, 3, 4, 5, 6]

包含数字的列表和包含字符串的列表进行“*”操作:

>>> numbers_list = [1] * 3

>>> strings_list = ['Python'] * 3

>>> numbers_list

[1, 1, 1]

>>> strings_list

['Python', 'Python', 'Python']

>>> numbers_list[0] = 3

>>> strings_list[0] = 'C'

>>> numbers_list

[3, 1, 1]

>>> strings_list

['C', 'Python', 'Python']

4. 索引和切片

索引和切片都是通用的序列操作,因此,不仅列表有索引和切片,字符串也有索引和切片:

>>> word = 'Python'

>>> word[0]  # 第1个字符

'P'

>>> word[-2]  # 倒数第2个字符

'o'

>>> word[:2]  # 前2个字符

'Py'

>>> word[:2] + word[2:]  # 字符拼接

'Python'

>>> word[-3:]  # 后3个字符

'hon'

5. len()函数

len()函数用于获取序列的长度:

>>> words = """Python is a programming language that lets you work quickly and integrate systems more effectively."""

>>> len(words)

99

>>> lists_ = ['Python', 312, []]

>>> len(lists)

3

6. index()方法

序列中的index()方法用于查找第一个出现指定子序列的索引位置,如果不存在,那么会抛出ValueError异常:

>>> word = 'banana'

>>> word.index('a')

1

>>> word.index('na')

2

>>> word.index('an')

1

>>> word.index('c')

Traceback (most recent call last):

File "", line 1, in

ValueError: substring not found

index()方法也可以指定查找范围,即查找索引位置的起始值和结束值:

>>> numbers = [3, 1, 4, 1, 5]

>>> numbers.index(1)

1

>>> numbers.index(1, 2)

3

>>> word = 'banana'

>>> word.index('a', 2, 4)

3

7. count()方法

不仅仅是列表,每一种序列类型都有count()方法:

>>> word = 'banana'

>>> word.count('a')

3

>>> word.count('na')

2

>>> word.count('c')

0

>>> numbers = [1, 0, 1, 0, 1, 1]

>>> numbers.count(0)

2

>>> numbers.count(1)

4

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值