反转list
a = [1,2,3,4]
b = [5,6,7]
#reverse a list
print('reverse a list')
#use reversed method
print('list a is :%s' % a)
print('list a use reversed to reverse: ', list(reversed(a)))
#use slice method, a[start:stop:step]
print('list a use slice method to reverse: %s' % a[::-1])
#use new list to get the reverse result
c = []
for i in range(len(a)):
c.append(a[len(a)-1-i])
print('list a use new list to reverse is:', c)
运行结果:
合并list
#merge two lists
print('\n\n')
print('merge two lists')
#use append method
print('list a is :', a)
print('list b is:', b)
a.append(b)
print('use append to merge two list:', a)
#use extend method
a = [1,2,3,4]
b = [5,6,7]
a.extend(b)
print('use extend to merge two list:', a)
#use +
a = [1,2,3,4]
b = [5,6,7]
print('use + to merge two list:', a+b)
#use slice method
a = [1,2,3,4]
b = [5,6,7]
a[2:2] = b
print('use slice to insert list:', a)
运行结果:
list中删除元素
#delete element in list
print('\n\n')
print('delete element in list')
#use remove method
print(a)
a.remove(3)
print('remove 3 in list a:', a)
#use del method
del a[0]
print('delete first element in list a:', a)
#use pop method
print('the first element to pop is:', a.pop(0))
print('after pop-out the first element in list a:', a)
#use slice method
print('now , list a is:', a)
a[2:3]=[]
print('use slice to delete the 3rd element in list a:', a)
#use new list
c = []
for i in range(len(a)):
if a[i] == 4:
pass
else:
c.append(a[i])
print('use new list to delete element 4 in list a:', a)
#use clear method to clear list
print('now list a is:', a)
a.clear()
print('use clear method to delete list a:', a)
运行结果:
list中出现次数大于1的元素
#find the same element
print('\n\n')
print('find the same element in two list :')
a = [1,2,3,4]
b = [2,3,5,6,7]
print(a)
print(b)
print('the same element in two list :', [val for val in a if val in b])
print('the same element in two list use intersection method:', list(set(a).intersection(set(b))))
运行结果:
list去重
#del the duplicate element
print('\n\n')
print('del the duplicate element:')
a = [1,2,3,4,4,4,3,5,2,4]
print(a)
print('use set method:', list( set(a) ))
print('use function: ')
s = []
for ele in a:
if ele not in s:
s.append(ele)
print(s)
print('use new list and enumerate method:', [ele for n,ele in enumerate(a) if ele not in a[:n]])
print('use counter class:')
import collections
a = collections.Counter(a)
print(list(a.keys()))
#or use numpy.unique method
运行结果:
list排序
#sort
print('\n\n')
print('sort the list:')
a = [2,3,1,6,5]
print('list a is : %s' % a)
print('list after sorting is :%s' % sorted(a))
运行结果:
string转为list
#transfer list to string
print('\n\n')
print('transfer list to string:')
a = [1,2,4,5,3,2,1,2]
print('list a is :', a)
print('list a transfer to string:', ','.join(map(str,a)))
运行结果: