简体   繁体   中英

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.

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) :

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 : .

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 * :

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']

Please reference code below:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM