Сравнение общих элементов между 2 списками - PullRequest
96 голосов
/ 19 мая 2010
def common_elements(list1, list2):
    """
    Return a list containing the elements which are in both list1 and list2

    >>> common_elements([1,2,3,4,5,6], [3,5,7,9])
    [3, 5]
    >>> common_elements(['this','this','n','that'],['this','not','that','that'])
    ['this', 'that']
    """
    for element in list1:
        if element in list2:
            return list(element)

Понял, но пока не могу заставить его работать!

Есть идеи?

Ответы [ 17 ]

1 голос
/ 29 ноября 2018

Ваша проблема в том, что вы возвращаетесь из цикла for, поэтому вы получите только первое совпадение. Решение состоит в том, чтобы переместить ваше возвращение за пределы цикла.

def elementosEnComunEntre(lista1,lista2):

    elementosEnComun = set()

    for e1 in lista1:
         if(e1 in lista2):
             elementosEnComun.add(e1)

    return list(elementosEnComun)
1 голос
/ 04 апреля 2018
a_list = range(1,10)
b_list = range(5, 25)
both = []

for i in b_list:
    for j in a_list:
        if i == j:
            both.append(i)
1 голос
/ 27 января 2016

Вот довольно грубый метод, который я придумал.Это, конечно, не самый эффективный, но это что-то.

Проблема, которую я обнаружил с некоторыми решениями, заключается в том, что либо она не дает повторяющихся элементов, либо не дает правильного количества элементов, когда порядок ввода имеет значение.

#finds common elements
def common(list1, list2):
    result = []
    intersect = list(set(list1).intersection(list2))

    #using the intersection, find the min
    count1 = 0
    count2 = 0
    for i in intersect: 
        for j in list1:
            if i == j:
                count1 += 1
        for k in list2: 
            if i == k:
                count2 += 1
        minCount = min(count2,count1)
        count1 = 0
        count2 = 0

        #append common factor that many times
        for j in range(minCount):
            result.append(i)

    return result
1 голос
/ 18 апреля 2018
f_list=[1,2,3,4,5] # First list
s_list=[3,4,5,6,7,8] # Second list
# An empty list stores the common elements present in both the list
common_elements=[]

for i in f_list:
    # checking if each element of first list exists in second list
    if i in s_list:
        #if so add it in common elements list
        common_elements.append(i) 
print(common_elements)
1 голос
/ 15 сентября 2018
list_1=range(0,100)
list_2=range(0,100,5)
final_list=[]
for i in list_1:
    for j in list_2:
        if i==j:
            final_list.append(i)
print(set(final_list))
1 голос
/ 09 сентября 2018
def common_member(a, b): 
    a_set = set(a) 
    b_set = set(b) 
    if (a_set & b_set): 
        print(a_set & b_set) 
    else: 
        print("No common elements") 
1 голос
/ 23 июля 2018

Привет, это мое предложение (очень просто)

import random

i = [1,4,10,22,44,6,12] #first random list, could be change in the future
j = [1,4,10,8,15,14] #second random list, could be change in the future
for x in i: 
    if x in j: #for any item 'x' from collection 'i', find the same item in collection of 'j'
        print(x) # print out the results
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...