Python list常用操作

#init a list
l = ['a', 'b', 'c']

#index
print (l[0])

#negative index
print (l[-1])

#print (l[-4]) 
#IndexError

#切片
l[0:3]
l[0:-1]

# 获取列表长度
len(l)

#concation
[1, 2, 3] + [3, 4, 5]
[1, 2, 3] * 3

# delete
del l[2]

# iteration
for i in l:
    print (i)

for i in range(len(l)):
    print(l[i])

# in
'a' in [l]

#multiple assignment trick
tmp = [1, 2, 3]
a, b, c = tmp

#index, if the values are not in the list, python will raise a ValueError Exception
tmp.index(1)

#append(in place)
tmp.append(4)

#insert (in place)
tmp.insert(5, 5) #index value

#remove(in place)
tmp.remove(5)

#sort (in place)
tmp.sort()
tmp.sort(reverse = True)

strList = ['a', 'b', 'A', 'B']
strList.sort(str.lower)

import random
messages = ['dfdk', 'dffd', 'df']
print(messages[random.randint(0, len(messages) - 1)])

#tuple a immutable type of list
t = ('egg', 1, 2)

#只有一个元素的tuple
t = ('egg', )

#Converting Type 
str(42) #'42'
tuple(['a', 'b', 'c'])
list (('a', 'b', 'c'))
list('hello')

import copy
spam = ['a', 'b', 'c']
cheese = copy.copy(spam)
cheese1 = copy.deepcopy(spam)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容