![](/img/trans.png)
[英]How to remove element from list if element is present in list Python
[英]How to remove list element from list of list in python
我试图从python中的列表列表中删除第三个和第四个列表。
我的清单如下:
List = [
['101', 'Dashboard', '1', '1'],
['102', 'Potential Cstomer', '1', '1'],
['102-01', 'Potential Cstomer', '1', '1'],
['102-02', 'Potential Cstomer Activity', '1', '1']
]
删除列表的第三和第四个元素后,我想这样:
NewList = [
['101', 'Dashboard'],
['102', 'Potential Cstomer'],
['102-01', 'Potential Cstomer'],
['102-02', 'Potential Customer Activity']
]
我尝试了下面的代码,但没有做任何改动。
NewList = [list(element) for element in List if element[0] or element[1]]
print NewList
我应该如何更改当前代码以达到预期结果? 谢谢。
在列表 推导中切片每个嵌套列表。 切片表示法从索引0开始,并在1处停止,即[0, 2)
:
NewList = [element[:2] for element in List]
如果未指定开始索引,它将被视为None
这是相同的列表的起始索引时None
前的第一次出现:
。
如同:
NewList = [element[slice(None, 2)] for element in List] # More verbose
在Python 3中,您可以使用扩展解包来实现应用'splat'运算符*
:
NewList = [elements for *elements, _, _ in List]
这个怎么样:
for s in List:
del s[3]
del s[2]
删除到位。
此解决方案使用负索引来允许任意长度子列表,同时保持两个尾随数字的原始条件。
List = [
['101', 'Dashboard', '1', '1'],
['102', 'Potential Cstomer', '1', '1'],
['102-01', 'Potential Cstomer', '1', '1'],
['102-02', 'Potential Cstomer Activity', '1', '1']
]
new_final_list = [i[:-2] for i in List]
for i in new_final_list:
print(i)
输出:
['101', 'Dashboard'],
['102', 'Potential Cstomer']
['102-01', 'Potential Cstomer']
['102-02', 'Potential Cstomer Activity']
Names = [["Tom", 32, 12], ["John", 54, 16], ["James", 52, 15]]
Names_new = []
for i in Names:
# print(i + )
del i[0]
Names_new.append(i)
print(Names_new)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.