||
# 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'
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-6-5 03:43
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社