I have a list of expressions, in an array known as literals
:
literals = ['-PacketAt(A)', '+CarAt(B)', '-CarAt(A)', '-PacketInCar', '+PacketAt(B)', '+CarAt(A)', 'LoadA', '+PacketAt(A)', '+PacketInCar', 'LoadB', '-PacketAt(B)', 'DriveAB', '-CarAt(B)', 'DriveBA', 'ProduceA', 'DischargeA', 'DischargeB']
I would like to remove the elements of the array that do not start with a +
and -
sign.
I have written the following to try to do that:
for literal in literals:
if not (literal.startswith('-')) and not (literal.startswith('+')):
literals.remove(literal)
However, after I run this for loop, I receive the following output:
literals = ['-PacketAt(A)', '+CarAt(B)', '-CarAt(A)', '-PacketInCar', '+PacketAt(B)', '+CarAt(A)', '+PacketAt(A)', '+PacketInCar', '-PacketAt(B)', '-CarAt(B)', 'ProduceA', 'DischargeB']
The desired output is:
literals = ['-PacketAt(A)', '+CarAt(B)', '-CarAt(A)', ' -PacketInCar', '+PacketAt(B)',
'+CarAt(A)', '+PacketAt(A)', '+PacketInCar', '-PacketAt(B)', 'DriveAB', '-CarAt(B)']
From this, 'ProduceA'
and 'DischargeB'
should not be in the list known as literals
, but they are. Why is this so, and how can I modify my code such that they do not appear? Here is some runnable test code I have provided:
literals = ['-PacketAt(A)', '+CarAt(B)', '-CarAt(A)', ' -PacketInCar', '+PacketAt(B)',
'+CarAt(A)', 'LoadA', '+PacketAt(A)', '+PacketInCar', 'LoadB', '-PacketAt(B)', 'DriveAB', '-CarAt(B)', 'DriveBA', 'ProduceA', 'DischargeA', 'DischargeB']
for literal in literals:
if not (literal.startswith('-')) and not (literal.startswith('+')):
literals.remove(literal)
print(literals)
and an online Python IDE to run it in: https://www.programiz.com/python-programming/online-compiler/
The issue you're having is that your are trying to remove elements from a list while iterating the list. Try to avoid this.
You can use list comprehension to get the results:
literals = ['-PacketAt(A)', '+CarAt(B)', '-CarAt(A)', ' -PacketInCar', '+PacketAt(B)', '+CarAt(A)', 'LoadA', '+PacketAt(A)', '+PacketInCar', 'LoadB', '-PacketAt(B)', 'DriveAB', '-CarAt(B)', 'DriveBA', 'ProduceA', 'DischargeA', 'DischargeB']
lst = [x for x in literals if x[0] in ['-','+']]
print(lst)
Output
['-PacketAt(A)', '+CarAt(B)', '-CarAt(A)', '-PacketInCar', '+PacketAt(B)', '+CarAt(A)', '+PacketAt(A)', '+PacketInCar', '-PacketAt(B)', '-CarAt(B)']
I will use a list comprehension:
literals = ['-PacketAt(A)', '+CarAt(B)', '-CarAt(A)', '-PacketInCar', '+PacketAt(B)', '+CarAt(A)', 'LoadA', '+PacketAt(A)', '+PacketInCar', 'LoadB', '-PacketAt(B)', 'DriveAB', '-CarAt(B)', 'DriveBA', 'ProduceA', 'DischargeA', 'DischargeB']
literals = [x for x in literals if not x.startswith(('-','+'))]
print(literals)
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.