Search a string in a list - python

I am comparing two lists of the same structure, one with a complete set of data, and one with a subset of .list_a and a complete list, and list_b is a subset. The result should be list_c with lines that differ or not in list_b.

for row_a in file_a:
    for row_b in file_b:
        if row_a != row_b:
            file_c.append(row_a)

If errors, which are erroneous because file_c has several times the values ​​of file_a and file_b.

+4
source share
3 answers

Python actually has a structure structure set. Maybe it would be useful to use it in your case?

file_a = ['a', 'b', 'c']
file_b = ['b']
set(file_a).difference(file_b)
Out[4]: {'a', 'c'}
list(set(file_a).difference(file_b))
Out[5]: ['a', 'c']
+3
source

Of course, there are better ways to do the job, but the following:

file_c.extend((row for row in file_a if row not in file_b))
+2
source

- :

file_c = list(set(file_a) - set(file_b))

, . , ,

list(set(file_a).difference(file_b)) 

erhesto. , , ().

Well, after testing, this is what I learned. I installed two different files sub.py and dif.py

Outputs:

   swift@pennywise practice $ time python sub.py
[27, 17, 19, 31]

real    0m0.055s
user    0m0.044s
sys 0m0.008s
swift@pennywise practice $ time python dif.py
[17, 19, 27, 31]

real    0m0.056s
user    0m0.032s
sys 0m0.016s

The body of the .py files:

sub.py:

#!/usr/bin/python3.6
# -*- coding utf-8 -*-


def test():
    lsta = [2, 3, 5, 7, 9, 13, 17, 19, 27, 31,]
    lstb = [2, 3, 5, 7, 9, 13,]

    lstc = list(set(lsta) - set(lstb))

    return lstc

if __name__ == '__main__':
    print(test())

dif.py

#!/usr/bin/python3.6
# -*- coding utf-8 -*-


def test():
    lsta = [2, 3, 5, 7, 9, 13, 17, 19, 27, 31,]
    lstb = [2, 3, 5, 7, 9, 13,]

    lstc = list(set(lsta).difference(lstb))

    return lstc

if __name__ == '__main__':
    print(test())

Edited because I understood the error - forgot to execute the program!

The suboperator is significantly faster on the system than set.difference. So, I would probably stick with '-' compared to set.difference ... it's easier for me to read what happens.

The source for the set () function is set (): fooobar.com/questions/17273 / ...

0
source

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


All Articles