为了账号安全,请及时绑定邮箱和手机立即绑定

如何从二维列表中去除第一列?

如何从二维列表中去除第一列?

慕虎7371278 2023-06-06 17:30:20
尝试从 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","juice this"], ["orange","lemonade this"], ["kiwi","punch this"]]只从第一列而不是第二列剥离“this”。最好甚至不检查其他列。
查看完整描述

4 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

使用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])


查看完整回答
反对 回复 2023-06-06
?
慕侠2389804

TA贡献1719条经验 获得超6个赞

尝试这个

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


查看完整回答
反对 回复 2023-06-06
?
POPMUISE

TA贡献1765条经验 获得超5个赞

您可以使用

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



查看完整回答
反对 回复 2023-06-06
?
慕莱坞森

TA贡献1810条经验 获得超4个赞

你可以试试这个。这行代码将删除

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



查看完整回答
反对 回复 2023-06-06
  • 4 回答
  • 0 关注
  • 149 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信