如何从2D列表中删除第一列?

问题描述

尝试从2D列表中剥离字符串,但仅在第一列中

我的尝试:

list = [[x.strip('this') for x in y[0]] for y in list]

示例列表:

[["apple this","juice this"],["orange this","lemonade this"],["kiwi this","punch this"]]

想要的结果:

[["apple",["orange",["kiwi","punch this"]]

仅在第一列中加上“ this”,而不是第二列。

最好甚至不检查其他列。

解决方法

使用split()zip()

ee = [["apple this","juice this"],["orange this","lemonade this"],["kiwi this","punch this"]]

splitted = [x[0].split()[0] for x in ee]  # ['apple','orange','kiwi']
later_lst = [x[1] for x in ee]  # ['juice this','lemonade this','punch this']

print([list(l) for l in zip(splitted,later_lst)])

输出:

[['apple','juice this'],['orange','lemonade this'],['kiwi','punch this']]

单线:

print([list(l) for l in zip([x[0].split()[0] for x in ee],[x[1] for x in ee])])

编辑

更短版本:

print([[x[0].split()[0],x[1]] for x in ee])
,

尝试一下

list = [[(x if i else x.strip()) for i,x in enumerate(y)] for y in list]
,

您可以使用



list = [[x.strip('strip this') if j==0 else x for j,x in enumerate(y)] for y in list]
,

您可以尝试一下。这行代码将删除

[[i.replace(' this',''),j] for i,j in a]

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...