简体   繁体   中英

how can delete/remove values from list/set/dict in Python?

I created a list, a set and a dict and now I want to remove certain items from them

N = [10**i for i in range(0,3)] #range(3,7) for 1000 to 1M
    for i in N:
        con_list = []
        con_set = set()
        con_dict = {}
        for x in range (i): #this is the list
            con_list.append(x)
            print(con_list)
        for x in range(i): #this is the set
            con_set.add(x)
            print(con_set)
        for x in range(i): #this is the dict
            con_dict = dict(zip(range(x), range(x)))
            print(con_dict)

items to remove

n = min(10000, int(0.1 * len(con_list)))
indeces_to_delete = sorted(random.sample(range(i),n), reverse=True)

now if I add this:

for a in indeces_to_delete:
     del con_list[a]
     print(con_list)

it doesn't work

Need to do the same for a set and a dict

Thanks!

You can use pop On a dict:

d = {'a': 'test', 'b': 'test2'}

calling d.pop('b') will remove the key/value pair for key b

on list:

l = ['a', 'b', 'c']

calling l.pop(2) will remove the third element (as list index start at 0)

Beware on set:

s = {'a', 'b', 'c'}

calling s.pop() will remove a random element as discussed here: In python, is set.pop() deterministic?

you should use s.discard('a') to remove element 'a'

More infos here: https://docs.python.org/2/tutorial/datastructures.html

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