Перебор списков в серии, чтобы найти похожие элементы в списке в Python - PullRequest
0 голосов
/ 05 июля 2019

У меня есть серия, такая как:

ID
1 [a,b,c,d,e]
2 [b,c,d,e,f]
3 [z,t,c,d,w]

Я хочу распечатать общие элементы в списке

output: [b,c,d,e]

Кроме того, я хотел бы знать, какой идентификатор онивходили в вывод
:

b: 1,2
c: 1,2,3
d: 1,2,3
e: 1,2

Ответы [ 3 ]

1 голос
/ 05 июля 2019

Если вы создаете словарь, сопоставляющий индексы со списками символов, вы можете получить обе части своего ответа:

from collections import defaultdict
d = defaultdict(list)
arr = [
    ['a','b','c','d','e'],
    ['b','c','d','e','f'],
    ['z','t','c','d','w']
    ]

for ind, l in enumerate(arr):
    for c in l:
        d[c].append(ind)
print(d)

d будет словарь, подобный:

defaultdict(list,
            {'a': [0],
             'b': [0, 1],
             'c': [0, 1, 2],
             'd': [0, 1, 2],
             'e': [0, 1],
             'f': [1],
             'z': [2],
             't': [2],
             'w': [2]})

Элементы, которые появляются в более чем одном списке, можно найти по следующему адресу:

[k for k, v in d.items() if len(v) > 1]
# ['b', 'c', 'd', 'e']

Вы можете индексировать непосредственно в dict, чтобы найти индексы, частью которых они являются:

d['e']
# [0, 1]
0 голосов
/ 05 июля 2019

давайте попробуем подсчитать, так как нам нужна сложность времени.

l1 = ['a','b','c','d','e']
l2 = ['b','c','d','e','f']
l3 = ['z','t','c','d','w']

# create an empty dictionary
count = dict()

# start your id counter
list_id = 1    

# iterate over the lists
for lst in [l1,l2,l3]:
    # iterate over each list, getting the char
    for char in lst:
        try:
            # try to append the list id to each corresponding char
            count[char].append(list_id)
        except:
            # if the char key doesn't exist in the dict, we add it as a list
            # containing our list id in which it was first found
            count[char] = [list_id]
    # increment our list id, as we finished looking on li
    list_id = list_id + 1

# print each char and list that contains more than one list_id
for key in count:
    if len(count[key])>1:
        print(key+': '+str(count[key]))

Выход будет

b: [1, 2]
c: [1, 2, 3]
d: [1, 2, 3]
e: [1, 2]
0 голосов
/ 05 июля 2019

Добро пожаловать в StackOverflow.

Если я понимаю вашу проблему, вы можете использовать defaultdict для этого:

from collections import defaultdict

l1 = ['a', 'b', 'c', 'd', 'e']
l2 = ['b', 'c', 'd', 'e', 'f']
l3 = ['z', 't', 'c', 'd', 'w']

output = defaultdict(list)

for l in [l1, l2, l3]:
    for item in l:
        output[item].append(l)

output = [{k: v} for k, v in output.items() if len(v) == 3]

print(output)

Выходы:

[
  {'c': [['a', 'b', 'c', 'd', 'e'], ['b', 'c', 'd', 'e', 'f'], ['z', 't', 'c', 'd', 'w']]},
  {'d': [['a', 'b', 'c', 'd', 'e'], ['b', 'c', 'd', 'e', 'f'], ['z', 't', 'c', 'd', 'w']]}
]

Это отвечает на ваш вопрос?

...