Why is this code not working?
for a in massiv: for b in massiv: if len(a)> len(b): del b elif len(a)<len(b): del a
Why is this code not working?
for a in massiv: for b in massiv: if len(a)> len(b): del b elif len(a)<len(b): del a
The code does not work, because the del
instruction does not delete the element, but decreases the number of references to it by 1, del a
means that you need to reduce the number of references to the element of the list referenced by a
, but since in the list there is a link to this item, it is not deleted anywhere.
Strange logic in your script =). But still.
During the iteration over arrays in python, the removal of elements is not allowed. To do this, either make a copy of the list - massiv [:], or iterate the old-fashioned way - by indices. In the case of indexes, you get access to the elements of the original array.
massiv = ['12', '123', '1234'] for i in range(len(massiv) - 1): for j in range(len(massiv) - 1): if len(massiv[i]) > len(massiv[j]): del massiv[j] elif len(massiv[i]) < len(massiv[j]): del massiv[i] print massiv # => ['1234']
lst[:] = [max(lst, key=len)]
- jfsmaxlen= max([len(i) for i in massiv]) massiv=filter(lambda x: len(x)=maxlen, massiv)
for a in massiv: for b in massiv: if len(a)> len(b): massiv.remove(b) elif len(a)<len(b): massiv.remove(a)
There are more letters, but it became clear that where we are from and that, in general, this is a more correct approach ... but in general, based on the description of the topstarter, nothing is clear at all except that something doesn’t work for him ...
PS: write more details of the problem and problems;)
for a in massiv
- enumeration of the list. And here the "first comer"? And the first, and second, and third. Just for different values of massiv, the sequence of deletions will be quite bizarre. Perhaps correct, but the person who will force me to understand this, I will hardly be treated as a friend. Code - delete all items with a length less than the maximum. Maybe it works, but well, it nafig. - alexlzTo remove an item from the lst
list if its index i
is known:
del lst[i]
To remove all items except the item with the longest:
lst[:] = [max(lst, key=len)]
An idiomatic way to remove items from the list that satisfy a given condition, to collect the items that should be left and replace all the items in the list with them:
lst[:] = [item for item in lst if keep(item)]
lst[:] = filter(keep, lst)
- Andrio Skurfilter()
, but more often the expression is of the following type: if item and item[0]
- in this case it is better to use list comprehension instead of filter + lambda. - jfsIt should be like this:
for a in massiv: for b in massiv: if len(a)> len(b): del massiv[b] elif len(a)<len(b): del massiv[a]
Source: https://ru.stackoverflow.com/questions/81572/
All Articles