序列的操作详解

1序列基本操作:

#!/usr/bin/env python
# encoding: utf-8
#________________________________________________序列基础操作________________________________________________________________
classmates = ['Michael', 'Bob', 'Tracy','chen','chen','chen']

# 末尾追加元素
classmates.append('Adam')
print('追加后',classmates)

# 指定插入位置
classmates.insert(1,'Jack')
print ('指定位置插入后',classmates)

###删除指定元素(根据下标)
classmates.pop(1)
print('删除指定元素后',classmates)
# 删除指定元素(根据指定元素)
classmates.remove('Tracy')
print('删除指定元素后',classmates)
#删除序列下标元素
del classmates[1]
print('删除指定元素后',classmates)

#修改指定元素
classmates[1]='test001'
print ('修改指定元素后',classmates)

#index是查看元素的下标
print('先查看list',classmates)
print(classmates.index("chen"))

#统计元素出现的次数
print(classmates.count('chen'))


##########排序########################
print('排序前',classmates)
classmates.sort()#顺序
print('排序后',classmates)

# #日期排序操作
dict_key=['2022-03-10', '2022-03-13', '2022-03-14', '2022-03-15', '2022-03-16']
classmates.sort(reverse = True)#倒序
print(dict_key)
#备注char类型不能联合int使用

#两个list拼接
a=[11,12,13]
b=['name','age']
c=a+b
print('两个list拼接',c)


###______________________________________________________切片操作______________________________________________________________
w = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack','chen','dalan','abb']
print(w[2])#获取第2个元素
print(w[1:-2])#获取1到倒数第2个
print(w[2:4])#获取2到4个元素
print(w[-3:])#获取后3个元素
print(w[-3])#获取倒数第3个元素
print(w[:-3])#获取元素、排除后3个元素
print(w[::-1])#倒序显示序列
print(w[::-2])#-2为步值,表示倒序 并隔2取值
print(w[:1:-2])#-2为步值,表示倒序 并隔2取值(到1就停止))


###________________________________________________list其他基础用法_______________________________________________________________________
a=[5,3,9,12,7]
b=[3,6,6,3,7,4,2]

###统计list元素的和(用于list元素为int类型)
print("list元素累加&求和(int类型):",sum(a))

###list去重操作
print("list去重:",list(set(b)))

###list的append追加(append方法用于追加单个元素,当追加一个列表时 会当作一个元素嵌套)
c=[1,2,3];d=[1,2]
c.append(a)#追加一个列表到c
d.append("32") #追加一个元素到d
print("追加一个列表后打印c:",c)
print("追加一个元素后打印d:",d)

###list的extend追加(用于追加一个可迭代对象的元素)
e=[1,2,3]
e.extend(a)#它会将列表中的每个元素都添加到目标列表中,而不会将整个列表作为一个元素添加。
print(e)

 

2.迭代器转数据类型:

dalan='hdhdwhdwe'

#______迭代器转换______________________
print(type(iter(dalan)))
print(type(dalan.__iter__()))

 

3.list拆分在组装:

#_________________________________把list按分号拆分在形成list_______________________________________________________
aa11=['assets/game/resource/shj_assets/picture/bigbg/create_role_bg1_ed9d9ee8.png;assets/game/resource/shj_assets/picture/bigbg/create_role_bg2_fc4b58f.png','assets/game/resource/loginres/login_bg_f_44ae01ef.jpg','333333']
cc=[]
for aa in aa11:
    bb= aa.split(';') if ';' in aa else aa.split()
    cc+=bb
    #print(cc)打印每次累加

#打印最终结果
print(cc)


#___________________________________________________1累加到100的和_______________________________________
coun=0
for i in range(1,101):
    coun+=i
print(coun)

 

4.列表组合

#!/usr/bin/python
# -*- coding: UTF-8 -*-

###____________________字符串组合成list(不重复)__________________________________
def perms(s=''):
    if len(s) <= 1:  # 长度为1的字符串,排列组合就是自己
        return [s]
    sl = []  # 放结果
    for i in range(len(s)):  # 第一个数的可能取值
        for j in perms(s[0:i] + s[i + 1:]):  # 排除第一个数
            sl.append(s[i] + j)
    return (list(set(sl)))


perm_nums = perms('123')
print('字符串组合结果:', len(perm_nums), perm_nums)



###______________________字符字符串组合成list(不重复)______________________________
'''perm和上面perms区别,转成了int类型,列表元素也是int'''
def perm(s=""):
    if len(s) <= 1:
        return [s]
    else:
        s1 = []
        for i in range(len(s)):
            for j in perm(s[0:i] + s[i + 1:]):
                s1.append(s[i] + j[:2])
        return (list(set(s1)))


perm_num = perm("123")
m = list(map(int, perm_num))  # map函数把list中的字符串转化成int
print(len(perm_num), m)



#_________________________一个列表组合成多个列表(方法一)___________________________
'''http://www.360doc6.net/wxarticlenew/882598242.html'''
def list_name(name):
    result=[]
    for i in name:
        for j in name:
            for k in name:
                if len(set((i,j,k)))==len(name):
                    result.append([i,j,k])
    return result

num_list=[1,2,3]
res=list_name(num_list)
print(f"列表组合组合方法一:{res}")



#_________________________一个列表组合成多个列表(方法二)___________________________
#encoding =utf-8
num_list = [1,2,3]
def permute(nums):
        from itertools import permutations
        result = []
        for i in permutations(nums,len(nums)):
            result.append(list(i))
        return result
print('列表组合方法二:',permute(num_list))


#____________________________一个列表组合成多个列表(方法三)__________________________
import string
num_list = [1,2,3]
length = len(num_list)
var = tuple([string.ascii_lowercase[i] for i in range(length)])#生成字母代表的变量序列
temp = "["+','.join(var)+"]"
result = eval("["+temp+''.join(['for %s in num_list '%i for i in ''.join(var)])+'if len(set(%s))==3'%temp+"]")
print('列表组合方法三:',result)



#____________________________一个列表组合成多个列表(方法四)__________________________
#encoding =utf-8
num_list = [1,2,3]
def permute(nums):
        from functools import reduce
        result = [list(i) for i in reduce(lambda x,y:[str(a)+str(b) for a in x for b in y if str(b) not in str(a) ],[nums]*len(nums))]
        return result
print('列表组合以字符串方式:',permute(num_list))

 

 5.列表去重&两列表筛选

#!/usr/bin/python
# -*- coding: UTF-8 -*-
#_____________在两个列表都存在的元素________________________
list1 = [1, 2, 3, 4,"kill","kiss",5,"chenwei"]
list2 = [4, 5, 6,"test","ppp", 7, 8,"chenwei"]
common_elements = [x for x in set(list1) if x in list2]
print("两个列表同时存在的元素:",common_elements)


#_____________在list1存在,list2不存在的元素_________________
list1 = [1, 2, 3, 4,"kill","kiss",5,"chenwei"]
list2 = [4, 5, 6,"test","ppp", 7, 8,"chenwei"]
result = [x for x in list1 if x not in list2]
print("在list1存在,list2不存在的元素:",result)


#_____________在list1不存在,list2存在的元素_________________
list1 = [1, 2, 3, 4,"kill","kiss",5,"chenwei"]
list2 = [4, 5, 6,"test","ppp", 7, 8,"chenwei"]
result = [x for x in list2 if x not in list1]
print("在list1不存在,list2存在的元素:",result)


#__________________列表去重________________________________
test=[2,8,"test1",8,"chen","hallo word","test1"]
print("转为集合:",set(test))
print("先转集合去重,在转成list:",list(set(test)))

 

 6.list过滤处理

###_____________________________过滤list中指定的元素_____________________________________
s=['2022-03-09', '2022-03-10', '2022-03-14', '2022-03-14','', '', '\n','chen','2022-03-15']

#过滤list为“”的元素
comp = [x for x in s if x != '']
print("过滤list的空白字符",comp)

###过滤list为 空白&chen&\n的元素
chen_list = [x for x in s if x != '' if x !="chen" if x !='\n']
print("过滤list为 空白&chen&\\n的元素",chen_list)

###list去重操作
list_set=list(set(s))
print("通过集合去重:",list_set)

###______________________________判断list是否为空__________________________________________
cc=['abc','chenwei','']
##方式一
if len(cc):
      print('cc不为空')
else:
      print('cc为空')

###方式二
if cc:
     print('cc不为空')
else:
     print('cc为空')

###方式三(判断list所有元素是否有空)
if all(cc):
     print('全部元素不为空时,结果Ture')
else:
     print('有任何一个元素为空,结果为False')


###方式四:
my_list = []
if bool(my_list) == False:
  print("列表为空")
###______________________________判断两个list是否相等_______________________________________ ###案例一(jieguo等于true表示相等) aa=['chenwei','chen'] bb=['chenwei','chen'] cc=['chen','chenwei'] jieguo=aa==bb print(jieguo) ###案例二(需要 import operator ) # print(operator.eq(aa,bb)) ###案例三 (需要顺序相同) if aa == bb: print("两个list相等(需要list顺序相同)") else: print("两个list不相等") #方案四 (元素顺序不同也可判断) if sorted(aa) == sorted(cc): print("两个list相同(元素顺序不同也可判断)") else: print("两个list不相同") ###__________________________过滤list元素里的字符,然后拆分____________________________________________ All_Package=['package:com.chen.cn\n','package:com1234.cn\n'] name=[''.join([i for i in price.replace("package:",'').split('\n')]) for price in All_Package] print(name) ###列表解析式: list=['package:com.crd_cn\n', 'package:com.555ap\n', 'package:com.mi.shop\n'] print([''.join([i for i in price.replace("package:",'').split('\n')]) for price in list]) ###普通方式: aaa=[] for i in list: aaa.append(i.replace("package:",'').strip('\n'))#先指定字符删除,然后去掉末尾换行,再追加到list print(aaa) #______________________________过滤嵌套list元素______________________________________________ aaa=[{'项目': 'QQ', '用例编号': 'test_001', '用例名称': '获取QQ号'}, {'项目': '小飞机', '用例编号': 'test_002', '用例名称': '登录平台'}, {'项目': '小飞机', '用例编号': 'test_003', '用例名称': '登录平台'}] print("查看list元素数:",len(aaa)) #过滤掉"用例编号"不等于”test_003“的元素 bbbb = [item for item in aaa if item.get('用例编号') != 'test_003'] print("过滤掉用例编号不等于test_003的元素:",bbbb)

 

7列表转字典

##_______________________________________两个普通列表转字典________________________________________________________
aa=["name","age","sehngao"]
bb=["张三",25,"163cm"]
#方式一通过zip:
dict1=dict(zip(aa,bb))
print("两个列表转字典",dict1)

#方式二通过循环
result = {}
for i in range(len(aa)):
    result[aa[i]] = bb[i]
print("转换后的字典",result)


##______________________________________二维数组转字典_____________________________________________________________
my_list = [("a", 1), ("b", 2), ("c", 3)]
#方式一 强转换
my_dict = dict(my_list)
print("转换后字典",my_dict)

#方式二循环转换
my_dict = {key: value for key, value in my_list}
print("转换后字典11",my_dict)

 

8.列表中级操作

#__________________________________________________序列中级操作__________________________________________________________________
#判断list包含某个元素
names1=["Alice","Linda","Bob"]
if "Alice" in names1:
    print(True)
else:
    print(False)

#判断list包含某个元素(使用三元表达式)
res=["Alice","Linda","Bob"]
boj= True if "Alice" in res else False
print(boj)


#list是否包含某个字符串
abc=['chen','chenwei','www','wedd']
a3 = [i for i in abc if 'chen' in i]
print('包含chen的元素有',a3)


#两种获取字符串的方式
a='python'
c=len(a)
for letter in range(c):     # 第一种方式
   print ('当前字母..... :', a[letter])

for letter in a:     # 第二种方式
   print ('当前字母 :', letter)


#序列、元组拼接
chen=('wei','haha',26,'nini',77)
print (chen)
wei=('tata',22,'nini')
chenwei=chen+wei #元组连接,列表也可以连接
print (chenwei)



#_____________________________________________________遍历_______________________________________________________________________
#字典遍历(转成list)
dic = {'tom':11, 'sam':57,'lily':100}
for (key,value) in dic.items():
   print("这是key:" , key)
   print("这是key的value:" ,value)


#序列遍历方式1
fruits = ['banana', 'apple',  'mango','mangao']
for x in fruits:
   print ('当前水果 :', x)
print ("Good bye!")

#序列遍历方式2
fruits = ['banana', 'apple',  'mango','mangao']
a=len(fruits)
for b in range(a):
    print(fruits[b])



#___________________________________________________列表解析______________________________________________________________________
aaa=[a for a in range(1,10)]#序列解析
print (aaa)


#在1-10中求出大于4的平方(列表生成方式_)
oo=[i**2 for i in range(1,11) if i>=4]#通过列表解析求出
print (oo)

#在1-10中求出大于4的平方(普通模式)
L = []
for i in range(1,11):#普通序列求出
   if i >= 4:
      L.append(i**2)
print(L)


#生成1到10的list(列表生成方式_)
chen=list(range(1, 11))#第一种
print(chen)

#生成1到10的list(普通模式)
k=[]
for i in range(1,11):#第二种
    k.append(i)
print(k)

 

 9.二维列表&一维列表转换及操作

备注:二维列表又称嵌套列表,列表也可以叫数组

#_______________________________________________________二维数组__________________________________________________________________
#....................二维数组(嵌套list) 转一维数组...............
wei=(('2022-03-13', 29), ('2022-03-14', 22), ('2022-03-15', 21), ('2022-03-16', 18))
list1 = [i[0] for i in wei]
list2 = [i[1] for i in wei]
print('嵌套list转普通list',list1)
print('嵌套list转普通list',list2)


#..................二维数组(获取指定数组或元素)...................
L = [
    ['Apple', 'Google', 'Microsoft'],
    ['Java', 'Python', 'Ruby', 'PHP'],
    ['Adam', 'Bart', 'Lisa']
]
print("获取第2个列表:",L[2])
print ("获取第2个列表第0个元素:",L[2][0])


#...........遍历二维数组& 把二维转成一维数组....................
L = [
    ['Apple', 'Google', 'Microsoft'],
    ['Java', 'Python', 'Ruby', 'PHP'],
    ['Adam', 'Bart', 'Lisa']
]
sum_list = []
for i in range(len(L)):
    for j in range(len(L[i])):
        print(L[i][j])
        sum_list.append(L[i][j])
print("遍历后一维list", sum_list)


#...................两个list转成二维list/嵌套list...................
'''append:用于追加单个元素,   追加整个列表会嵌套
extend用于最近整个列表不会嵌套, 追加单个字符串会被拆分
'''
#append以嵌套方式插入(一个元素时就不会嵌套)
aa=['name','age','shengao']
bb=["张三",25,"170cm"]
aa.append(['chen','1234'])
#aa.append('1234')#单元素追加,不会嵌套
print("嵌套方式追加",aa)

#extend追加不会嵌套
aa1=['name','age','shengao']
bb1=["张三",25,"170cm"]
bb1.extend(aa1)
print("追加整个列表不会嵌套",bb1)

 

 

 

相关连接:

https://www.jianshu.com/p/6caf8215a5b1  .........................................................三维数组

 

posted on 2017-12-26 14:23  chen_2987  阅读(159)  评论(0编辑  收藏  举报

导航