"for" loop and "if" condition for creating a list in python

source=[1,2,3,4,2,3,5,6]

dst=[]
for item in source:
    if item not in dst:
        dst.append(item)

print(dst) # [1,2,3,4,5,6]

Can I simplify the code on something like this:

dst=[item for item in [1,2,3,4,2,3,5,6] if item not in 'this array']

thank

+4
source share
5 answers

This is probably the set you are looking for, since you cannot reference this array when creating it:

>>> source = [1,2,3,4,2,3,5,6]
>>> set(source)
{1, 2, 3, 4, 5, 6}

If you want to keep the original order, you can track what you have already added in dstwith the set ( seen):

>>> source = [1,2,3,4,2,3,5,6]
>>> seen = set()
>>> dst = []
>>> for i in source:
>>>     if i not in seen:
>>>         dst.append(i)
>>>         seen.add(i)
>>>
>>> dst
[1, 2, 3, 4, 5, 6]
+5
source

No, comprehension of lists cannot be self-reflective.

It seems you want to remove duplicates from the list. See this and this question for download approaches to this problem.

+6
source

dst , source, :

source = [1, 2, 3, 4, 2, 3, 5, 6]
dst = [item for i, item in enumerate(source)
       if item not in source[0:i]]

print(dst)  # [1, 2, 3, 4, 5, 6]
+3

if for, ?

[dst.append(item) for item in source if item not in dst]
0

Instead of creating a new list, you can modify the existing list with a list, as shown below:

In [1]: source
Out[1]: [1, 9, 2, 5, 6, 6, 4, 1, 4, 11]

In [2]: [ source.pop(i) for i in range(len(source))[::-1] if source.count(source[i]) > 1 ]
Out[2]: [4, 1, 6]

In [3]: source
Out[3]: [1, 9, 2, 5, 6, 4, 11]

As another approach, you can first get a unique list with a set, and then sort it with a reference to the original index value as follows:

source = [1, 9, 2, 5, 6, 6, 4, 1, 4, 11]
d = list(set(source))
d.sort(key=source.index)
print(d)  # [1, 9, 2, 5, 6, 4, 11]
0
source

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


All Articles