Python parsing list

I have a list in python that has the following entries

name-1

name-2

name-3

name-4

name-1

name-2

name-3

name-4

name-1

name-2

name-3

name-4

I would like to remove the name-1 from the list, except for its first appearance - the resulting list should look like

name-1

name-2

name-3

name-4

name-2

name-3

name-4

name-2

name-3

name-4

How to do it?

+3
source share
5 answers

Assuming name-1 stands for "first element":

[names[0]] + [n for n in names[1:] if n != names[0]]

EDIT: If the overall goal is to remove a duplicate of the entire list, just use set(names).

+2
source
def remove_but_first( lst, it):
    first = lst.index( it )
    # everything up to the first occurance of it, then the rest of the list without all it
    return lst[:first+1] + [ x for x in lst[first:] if x != it ]

s = [1,2,3,4,1,5,6]
print remove_but_first( s, 1)
+3
source

:

[name for cnt,name in enumerate(names) if (name != names[0] or cnt > 0)]

+2

, , . Python 2.5 :

def removeAllButFirst(elem, myList):
    idx = myList.index(elem)
    return myList[0:idx+1] + filter(lambda x: x != elem, myList[idx+1:])
+1
mylist = ['name-1', 'name-2', 'name-3', 'name-4', 'name-1', 'name-2', 'name-3', 'name-4', 'name-1', 'name-2', 'name-3', 'name-4']
newlist = filter(lambda x: x != 'name-1', mylist)
newlist.insert(mylist.index('name-1'), 'name-1')
print newlist
['name-1', 'name-2', 'name-3', 'name-4', 'name-2', 'name-3', 'name-4', 'name-2', 'name-3', 'name-4']
+1

Source: https://habr.com/ru/post/1741089/


All Articles