Should I use a dict or list?

I would like to go through a long list of two dimensions:

authors = [["Bob", "Lisa"], ["Alice", "Bob"], ["Molly", "Jim"], ... ]

and get a list containing all the names that the authors meet.

When I look through the list, I need a container to store the names that I have already seen, I wonder if I should use the list or the dict file:

with a list:

seen = []
for author_list in authors:
    for author in author_list:
        if not author in seen:
            seen.append(author)
result = seen

using dict:

seen = {}
for author_list in authors:
    for author in author_list:
        if not author in seen:
            seen[author] = True
result = seen.keys()

which one is faster? or are there better solutions?

0
source share
6 answers

set. , , , -. - (if element in my_set) O(1). , , , - ( O(n) .)

A dict set, , -. O(1). , set , dict , ( .)


set itertools.chain(), 2D- 1D-:

import itertools
seen = set()
for author in itertools.chain(*authors):
    seen.add(author)

:

import itertools
seen = set( itertools.chain(*authors) )

(, @jamylak) :

import itertools
seen = set( itertools.chain.from_iterable(authors) )

:

>>> a = [[1,2],[1,2],[1,2],[3,4]]
>>> set ( itertools.chain(*a) )
set([1, 2, 3, 4])

P.S.: , , collections.Counter, , .

:

>>> a = "DEADBEEF CAFEBABE"
>>> import collections
>>> collections.Counter(a)
Counter({'E': 5, 'A': 3, 'B': 3, 'D': 2, 'F': 2, ' ': 1, 'C': 1})
+8

set .

>>> authors = [["Bob", "Lisa"], ["Alice", "Bob"], ["Molly", "Jim"]]
>>> from itertools import chain
>>> set(chain(*authors))
set(['Lisa', 'Bob', 'Jim', 'Molly', 'Alice'])
+3

dict set, , list

import itertools
result = set(itertools.chain.from_iterable(authors))
+3

set -

from sets import Set

seen = Set()

for author_list in authors:
    for author in author_list:
        seen.add(author)

result = seen

"if", .

+2

, O (n), O (1).

.

+1

. , . , , - , , - , , , . .

. , , , , . ( ), , , , . ; Python ( , ), Python , .

, , , , . , , , . - , - . , .


, . , , , , .

; , , , . , . , " "; , True, ?

, OTOH, , .

+1

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


All Articles