Delete Python List Max String

Asked 2 years ago, Updated 2 years ago, 86 views

It's Python A = Delete the maximum string from the list ['c', 'bad', 'base', 'oracle', 'pandom'] (delete all strings of the same length if any) (ex. oracle and random)

I know the maximum string and I know the deletion, but since it's the maximum string (max function), only one is deleted, but how do I delete two (the same length string)? I tried to do my best, but I tried to remove a string with the same len length as below, but it doesn't work. I'm at a loss. Help me!

A = ['c', 'bad' , 'base', 'oracle', 'pandom']

for i in A:
    if len(i) == len(max(i)):
        A.remove(i)

print(A)

I'd appreciate it if you could tell me what to fix :)

python string list max remove

2022-09-20 17:05

2 Answers

If you use a for statement, for example, if it's a number, In order, 0, 1, 2, 3... Proceed in order.

But if the list element is deleted in the middle, the element stuck in the middle will not be checked.

For example, if you erase the third list element, the fourth list element is pulled to the third, so when you inspect the fourth list element, you inspect the fifth list element.

To avoid this problem, it's easier to make another list.

A = ['c', 'bad' , 'base', 'oracle', 'pandom']

b = [len(i) for i in A]
print(max(b))

c = []
for i in A:
    if len(i) < max(b):
        c.append(i)

print(A)
print(c)

>> 6
['c', 'bad', 'base', 'oracle', 'pandom']
['c', 'bad', 'base']


2022-09-20 17:05

>>> A = ['c', 'bad' , 'base', 'oracle', 'pandom']
>>> m = max(A, key=len)
>>> m
'oracle'
>>> A = [ e for e in A if len(e) < len(m) ]
>>> A
['c', 'bad', 'base']

It's like this if you use the list compliance in a more energetic way.


2022-09-20 17:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.