python关于列表的元素相同相加切片分组元素替换等问题

本文介绍了Python中列表的各种高级操作,包括利用列表推导式进行元素相加、按个数分组、统计相同元素个数、切片、部分替换以及快速删除元素等。详细讲解了不同场景下的实现方法,如需求是将列表元素前后相加,可以通过列表推导或itertools库实现。同时,文章还提供了具体的代码实例和示例分析。
摘要由CSDN通过智能技术生成

主要是利用列表推导式

举例一

a = [1,0,2]
b = [1,0,0]
x = [k for k in a if k in b]
print(x)

结果 [1, 0]

举例二

# 异向场景
a = [1,0,2]
b = [1,0,0]
x = [k for k in a if k not in b]
print(x)

结果:[2]

举例三

A = [113.0, -37.02, -33, 27666.48, 0.0, 2402.35, 8290.95]
B = [113.0, -37.02, 728.55, -33, 16.5, 27666.48, 0.0, 16.89, 2402.35, 8290.95]
if [i for i in B if i in A] == A:
    C = [i for i in B if i in A]
    print('计算正常')
else:
    C = [i for i in B if i not in A]
    print('计算不正常')
print(C)

结算结果:
计算正常
[113.0, -37.02, -33, 27666.48, 0.0, 2402.35, 8290.95]

举例四

a = [1, 2, 3]
b = [30, 50, 70]
url_1 = ['http://www.abc.gov.cn/search.jspx?page='+str(x) for x in a]
url_2 = ['&area='+str(x) for x in b]
url = [url_1[x]+url_2[x] for x in range(0,len(a))]
print(url)

结果
['http://www.abc.gov.cn/search.jspx?page=1&area=30', 'http://www.abc.gov.cn/search.jspx?page=2&area=50', 'http://www.abc.gov.cn/search.jspx?page=3&area=70']

举例五

a = [['11.0','12.25','13.22','14.32','15.0'],
     ['4.12','5.0','6.65','7.24','8.44'],
     ['0','1.2','2.44','3.63','4.55']]

代码是:
aa = {
   }
for i in a:
    b = 'co' + str(a.index(i))
    aa.update({
   b:i})
print(aa)

结果是:
{
   'co0': ['11.0', '12.25', '13.22', '14.32', '15.0'], 'co1': ['4.12', '5.0', '6.65', '7.24', '8.44'], 'co2': ['0', '1.2', '2.44', '3.63', '4.55']}

举例六

a = [['36049.00', '-3.52', '98.20', '-3.45', '17.50', '6308.57', '0.00', '2.1101', '760.66', '39810.60'],
     ['41662.00', '21.24', '90.02', '19.12', '17.50', '7290.85', '0.00', '2.1102', '879.15', '34138.40'],
     ['228583.00', '8.14', '90.03', '7.32', '17.50', '40002.02', '0.00', '2.1103', '4823.78', '183308.55'],
     ['274791.00', '-14.57', '90.04', '-13.11', '17.50', '48088.42', '0.00', '2.1104', '5799.18', '201840.25'],
     ['6246756.00', '-39.32', '90.06', '-35.41', '25.00', '1561689.00', '0.00', '2.1107', '131850.27', '3947239.20'],
     ['474715.00', '28.65', '90.05', '25.79', '17.50', '83075.12', '0.00', '2.1109', '10020.75', '354650.45'],
     ['4080431.00', '-37.64', '90.07', '-33.90', '25.00', '1020107.75', '0.00', '2.1111', '86141.97', '3529987.50'],
     ['407.00', '0.00', '90.08', '0.00', '25.00', '101.75', '0.00', '2.1113', '8.59', '0.00'],
     ['11383394.00', '-37.02', '-33.64', '2766663.48', '0.00', '240284.35', '8290974.95']]

需求:把a里面的列表里面所有的第一个元素的相加,第一个元素相加;也就是:36049.00+...+407.00最后的值等于[a0], 最后一行数据不用加,加完之后的数据保留两位小数,并且生成一个列表。[a[0],a[1]....]

s =[float(i[0]) for i in a[:-1]]
print(s)
输出结果:
[36049.0, 41662.0, 228583.0, 274791.0, 6246756.0, 474715.0, 4080431.0, 407.0]

s = [float(i) for i in a[-1]]
print(s
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值