python中列表相关操作

整理了下平时工作中常用的操作列表的方法
1、列表去重

alist=[1,2,3,1,2,1,1,1,1]
blist=list(set(alist))
print(blist)
# 得到[1, 2, 3]

2.求列表中列表的共有的元素

第一种

	p_list= [[1,2,3],[2,1,4],[5,7,1,2,1,1,1,3,3]]
	n = len(p_list)
	blist = []
	ins_list2 = []
	for i in p_list:
	    i = list(set(i))
	    for j in i:
	        blist.append(j)
	for k in blist:
	    m = blist.count(k)
	    if m == n:
	        ins_list2.append(str(k))
	ins_list2 = list(set(ins_list2))
	print(ins_list2)
	#['2', '1']

第二种

from collections import Counter   #引入Counter
a=[[1,2,3],[2,1,4],[5,7,1,2,1,1,1,3,3]]
c=[]
for i in a:
    i=list(set(i))
    for j in i:
        c.append(j)
b = dict(Counter(c))
n=len(a)
blist=[key for key,value in b.items()if value == n]
print (blist)  #只展示重复元素
# print ({key:value for key,value in b.items()if value > 1})  #展现重复元素和重复次数
# [1, 2]

3.两个列表对应元素相加

一
blist=[]
a = map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
for i in list(a):
    blist.append(i)
print(blist)
# [3, 7, 11, 15, 19]
二
knowledge_totals = reduce(lambda x, y: x + y, knowledge_list)
user_totals = reduce(lambda x, y: x + y, user_list)
  #相除后保留两位小数点(四舍五入)  
if user_total != 0:
 person_average = format(float(knowledge_total) / float(user_total), '.2f')
else:
	person_average = '0'

4.列表内字典排序后返回

result={}
result['data'] =[]
for i in range(5):
    time.sleep(1)
    create_time = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time()))
    result['data'].append({
        'create_time':create_time
    })
result['data'] = sorted(result['data'], key=lambda i: i['create_time'], reverse=True) # 倒序
print(result['data'])
# [{'create_time': '2020/06/01 14:05:58'}, {'create_time': '2020/06/01 14:05:57'}, {'create_time': '2020/06/01 14:05:56'}, {'create_time': '2020/06/01 14:05:55'}, {'create_time': '2020/06/01 14:05:54'}]

5.将字符串内id转为整型id或浮点型的元素的列表

y_individual_id = '1158, 1214, 1300, 1109, 1243, 1336, 1058, 1318, 1317, 1281'
y_individual_weight = '5, 10, 5, 30, 20, 3, 10, 3, 9, 5'
y_individual_id_list = list(map(int, y_individual_id.split(','))) if y_individual_id else ''
y_individual_weight_list = list(map(float, y_individual_weight.split(',')))

6.求列表内元素的值之和

score = float(y_weight) * float(i['property_value'])
data.append(float(score))
total=sum(data)

7.列表切片
[0:1:1] 开始索引(包括当前值)、结束索引(不包括当前值)、步长(包括结束索引值)
初阶:

a = ['a', 'b', 'c', 'd', 'e', 'f']
b = a[:3] # 结束索引(不包括当前索引,从0开始)
print(b)
#['a', 'b', 'c']
c = a[::2]#步长(开始索引,到结束索引的长度,包括结束索引)
print(c)
#['a', 'c', 'e']
d = a[::-1]#步长为负,则倒着取值,从右向左取值
print(d)
#['f', 'e', 'd', 'c', 'b', 'a']
d=a[-1] # 开始索引为1,倒着取值,从右向左取值
#['f']

进阶:

a = ['a', 'b', 'c', 'd', 'e', 'f']
c = a[1::2]
print(c)
#['b', 'd', 'f']
c2 = a[0::2]
print(c2)
#['a', 'c', 'e']
d = a[::-1]
print(d)
#['f', 'e', 'd', 'c', 'b', 'a']
e=a[1::-1] #'1'取到b,然后向左取一位,取到'a'
print(e)
#['b','a']

8.两个列表求交集,算法

def intersect(nums1, nums2):
    new_nums = []
    nums1.sort()
    nums2.sort()
    i, j = 0, 0
    while i < len(nums1) and j < len(nums2):
        if nums1[i] < nums2[j]:
            i += 1
        elif nums1[i] == nums2[j]:
            new_nums.append(nums1[i])
            i += 1
            j += 1
        else:
            j += 1
    return new_nums
a1=['1','3','2','1','5']
a2=['11','2','1','3','7','9']
a=intersect(a1,a2)
print(a)
#['1', '2', '3']

9.求多个列表去重之后的并集
两个列表

a=['1','2','3','4']
b=['1','3','5']
y=list(set(a).union(set(b)))
y.sort()
print(y)
#['1', '2', '3', '4', '5']

三个列表

x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"}
 
result = x.union(y, z) 
 
print(result)

输出结果为:

{'c', 'd', 'f', 'e', 'b', 'a'}

10.两个列表合并方法

切片,用运算符相加、extand 、append、zip
a.append(b)将b看成list一个元素和a合并成一个新的list
运算符相加 相加类似于两个列表连接,产生一个更大的新的列表
extand就是说把后一个b的元素拆开,放到a里面
所以说一般我们做项目for循环的时候很少会用到相加,相对来说会消耗更多的资源,因为它会产生…
切片

a=[1,2,3]
b=[4,5,6]
b[3:3]=a
b[len(b):len(b)]=a
print(b)
#[4, 5, 6, 1, 2, 3]

两个列表合并字典,用

a=['a','b','c']
b=['o','m','n']
c=dict(zip(a,b))
print(c)
#{'a': 'o', 'b': 'm', 'c': 'n'}

先打包,再降维.

a = [1,2,3]
b = [4,5,6]
c = zip(a,b) # c = [(1,4),(2,5),(3,6)]
list_new = [row[i] for i in range(len(0)) for row in c]

11.列表常用方法 b,d是数据 2是下标,即索引位置
alist.append(d) 末尾加数据
alist.extend(model) 末尾加列表
alist.insert(2,d) 索引位置插入数据
c=alist.pop(2) 获得并删除 默认最后一个
alist.remove(b) 从列表中删除数据
c=alist.count(b) 统计b出现的次数
c=index(b) 查询b的索引位置

12.将列表合并成字典
将列表a=[1,2,3],b=[4,5,6],合并成字典{1:4,2:5,3:6}
dict(zip(a,b))

c={}
for i in a:
f=a.index(i)
c[i]=b[f]
print©
13.将一个列表为0的元素全部删除
不产生新的列表版
a=[0,1,2,3,4,0,0,0]
for j in range(len(a)):
for i in a:
if i == 0:
a.remove(i)
print(a)
while 0 in a:
a.remove(0)
产生新的列表版
c={}
for i in a:
if i !=0:
c.append(i)
print©

14.整型、浮点型、字符串型的0

1.字符串的‘0’,是true;整型和浮点型的0、0.0都是false
2.浮点型的0.0==整数型的0。

a = 0
n = float(a)
print(n)
if n == 0:
print('1111')
if str(n) == '0':
print('2222')
if n:
print('3333')
if n == '0.0':
print('4444')
if str(n):
print('5555')

结果:

0.0
1111
5555

15.将列表内字典的值提取出来

[item[key] for item in Asin for key in item]
取出来之后,转浮点型
ind_list = [float(item[key]) for item in res for key in item]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值