haibaraxx的个人博客分享 http://blog.sciencenet.cn/u/haibaraxx

博文

Python 2: object.method(arguments)

已有 1954 次阅读 2016-11-18 19:32 |个人分类:Python|系统分类:科研笔记

# object.method(arguments)

>>> age=[7,16,18,24]
>>> age.append(30)
>>> age
[7, 16, 18, 24, 30]

>>> height=[158,161,164,170,187]
>>> age.extend(height)
>>> age
[7, 16, 18, 24, 30, 158, 161, 164, 170, 187]


>>> apples=['I','love','apples','apples','apples','now']
>>> apples.count('apples') # count how many times "apples" appears.
3
>>> apples('bow')
0

>>> apples.index('love') # index the position of "love" that firstly appears.
1
>>> apples.index('apples') # index the position of "apples" that firstly appears.
2
>>> apples.insert(1,'really') # insert 'really' and set in Position 1.
>>> apples
['I', 'really', 'love', 'apples', 'apples', 'apples', 'now']
>>> apples.reverse()
>>> apples
['now', 'apples', 'apples', 'apples', 'love', 'really', 'I']


# remove elements

# .pop() has an argument of the element's postion  to be removed and returns the removed elements.

>>> apples.pop(0)
'now'
>>> apples

['apples', 'apples', 'apples', 'love', 'really', 'I']

>>> apples.pop('really')

Traceback (most recent call last):
 File "<pyshell#112>", line 1, in <module>
   apples.pop('really')
TypeError: an integer is required


# .remove() has an argument of the element itself to be removed and do not return the removed elements.
>>> apples.remove('I')
>>> apples
['apples', 'apples', 'apples', 'love', 'really']['apples', 'apples', 'apples', 'love', 'really', 'I']

>>> apples.remove(-1)
Traceback (most recent call last):
 File "<pyshell#108>", line 1, in <module>
   apples.remove(-1)
ValueError: list.remove(x): x not in list


# 排序

>>> numbers=[21,34,12,3,2,5,8,98,76,58]
>>> numbers.sort() # For numbers, use .sort().
>>> numbers
[2, 3, 5, 8, 12, 21, 34, 58, 76, 98]

>>> string='Easybaby'

>>> sorted(string) # For strings, use sorted().
['E', 'a', 'a', 'b', 'b', 's', 'y', 'y'] # First principle, big letters followed by small letters; then in alphabetic sequence.

>>> string.sort()

Traceback (most recent call last):
 File "<pyshell#117>", line 1, in <module>
   string.sort()
AttributeError: 'str' object has no attribute 'sort'




https://wap.sciencenet.cn/blog-3031432-1015544.html

上一篇:Python 2: concatenate arrays
下一篇:RS: how to download MODIS-Aqua Level 2 data
收藏 IP: 134.1.1.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-6-5 03:43

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部