[英]How to remove list element from list of list in python
I tried to remove the third and the fourth list from the list of list in python. 我试图从python中的列表列表中删除第三个和第四个列表。
My list of list is below: 我的清单如下:
List = [
['101', 'Dashboard', '1', '1'],
['102', 'Potential Cstomer', '1', '1'],
['102-01', 'Potential Cstomer', '1', '1'],
['102-02', 'Potential Cstomer Activity', '1', '1']
]
After remove the third and fourth element of list, I would like to be like this: 删除列表的第三和第四个元素后,我想这样:
NewList = [
['101', 'Dashboard'],
['102', 'Potential Cstomer'],
['102-01', 'Potential Cstomer'],
['102-02', 'Potential Customer Activity']
]
I tried my code like below but it did not make any change. 我尝试了下面的代码,但没有做任何改动。
NewList = [list(element) for element in List if element[0] or element[1]]
print NewList
How should I change my current code to achieve my expected result? 我应该如何更改当前代码以达到预期结果? Thanks.
谢谢。
Slice each nested list in a list comprehension . 在列表 推导中切片每个嵌套列表。 The slice notation starts at index 0 and stops at 1 ie
[0, 2)
: 切片表示法从索引0开始,并在1处停止,即
[0, 2)
:
NewList = [element[:2] for element in List]
When the start index is not specified, it is taken as None
which is the same as start index of the list when None
appears before the first :
. 如果未指定开始索引,它将被视为
None
这是相同的列表的起始索引时None
前的第一次出现:
。
Same as: 如同:
NewList = [element[slice(None, 2)] for element in List] # More verbose
In Python 3, you could use extended unpacking to achieve the same thing applying the 'splat' operator *
: 在Python 3中,您可以使用扩展解包来实现应用'splat'运算符
*
:
NewList = [elements for *elements, _, _ in List]
How about this: 这个怎么样:
for s in List:
del s[3]
del s[2]
That deletes in place. 删除到位。
This solution uses negative indexing to allow for arbitrary length sublists, along as the original condition of two trailing digits is maintained. 此解决方案使用负索引来允许任意长度子列表,同时保持两个尾随数字的原始条件。
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)
Output: 输出:
['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.