美文网首页
Python list常用操作

Python list常用操作

作者: 一川烟草_满城风絮_梅子黄时雨 | 来源:发表于2018-05-13 20:39 被阅读0次
#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)

相关文章

网友评论

      本文标题:Python list常用操作

      本文链接:https://www.haomeiwen.com/subject/dhlfrftx.html