How to remove a list item with an eater

Asked 1 years ago, Updated 1 years ago, 107 views

Go to for in the list where you save the tuple I'm going to remove it if it meets certain conditions I don't know how to remove the tuple.

for tup in somelist:
    If condition (tup):
         #Remove the tuple

python iteration

2022-09-22 11:07

1 Answers

When I said I'd only run that code, somelist[:] = [x for x in somelist if not determine(x)] It's more Python-like writing.

The reason for writing [:] is to maintain reference.

For example, if you just put in the college entrance exam,

myList = [{1:2}, {3:4}]
otherList = myList

print "--original--"
print "myList:", myList
print "otherList:", otherList

myList = [tup for tup in myList if tup.has_key(1)]


print "--changed--"
print myList
print otherList

The results are

--original--
myList: [{1: 2}, {3: 4}]
otherList: [{1: 2}, {3: 4}]
--changed--
[{1: 2}]
[{1: 2}, {3: 4}]

However, when [:] is used,

myList = [{1:2}, {3:4}]
otherList = myList

print "--original--"
print "myList:", myList
print "otherList:", otherList

myList[:] = [tup for tup in myList if tup.has_key(1)]


print "--changed--"
print myList
print otherList

The results are

--original--
myList: [{1: 2}, {3: 4}]
otherList: [{1: 2}, {3: 4}]
--changed--
[{1: 2}]
[{1: 2}]

That's it. Can you see the difference between just using mylist= and writing mylist[:]=?


2022-09-22 11:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.