Removing a tuple from a list

这一生的挚爱 提交于 2019-12-12 03:47:38

问题


D = [(01294135018, "hello", 500)]
def pop(key, D, hasher = hash):
    try: 
        for item in D:
            if key in item:
                return item[2]
                D.remove(item)
                print(D) #Just to check if it has been removed

    except KeyError:
         pass

where key is the users choice, D is the list of tuples, and hasher is just equal to hash.

e.g pop("hello", D, hash), should remove the tuple from D, for example a tuple is currently a (hash(key), key, value)

so say there is a tuple in D (hash key value is random), for item in D, if the key in the item is equal to the one the user specifies, then return the "value" (item[2]) and remove the entire tuple, but it's not removing the tuple, D stays the same

e.g if I call the function

pop("hello", D, hasher) 

it doesn't work


回答1:


You can accomplish this with just a list comprehension:

[tuple([y for y in x if y != 'hello']) for x in D]

In this case it removes 'hello' from every tuple in D. And here you have it in function form:

def pop(key, D, hasher = hash):
    return [tuple([y for y in x if y != key]) for x in D]

Examples:

D = [(4135018, 'hello', 500), (12, 500, 'john')]
pop('john', D)

Output: [(4135018, 'hello', 500), (12, 500)]

D = [(4135018, 'hello', 500), (12, 500, 'john')]
pop(500, D)

Output: [(4135018, 'hello'), (12, 'john')]




回答2:


A function will not execute code after the return statement, you need to switch the remove and print with the return statement:

...
if key in item:
    D.remove(item)
    print(D)
    return item[2]
...

Still it is a bad idea to modify a list while looping through it.




回答3:


You need to remove your item before return:

if key in item:
    D.remove(item)
    return item[2]


来源:https://stackoverflow.com/questions/41383274/removing-a-tuple-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!