简体   繁体   English

在Python中找到两个列表之间的共同点

[英]Finding the common item between two list in python

Hey guys I need help on this past test question. 大家好,我在过去的测试问题上需要帮助。 Basically I am given two list of objects, and I am suppose to find the number of items that appear in the same position of the first list and the second. 基本上给了我两个对象列表,并且我想找到出现在第一个列表和第二个列表相同位置的项目数。 I have an example that was provided. 我有一个例子。

>>> commons(['a', 'b', 'c', 'd'], ['a', 'x', 'b', 'd'])
2
>>> commons(['a', 'b', 'c', 'd', 'e'], ['a', 'x', 'b', 'd'])
2

I am having trouble writing out the code. 我在写代码时遇到麻烦。 Our class is using python 3. I have no idea where to start writing this from. 我们的课使用的是python3。我不知道从哪里开始编写。 It is a first year programming course and I never did programming in my life. 这是一门第一年的编程课程,我一生中从未做过编程。

I think a more straightforward solution would be: 我认为更简单的解决方案是:

def commons(L1,L2):
    return len([x for x in zip(L1,L2) if x[0]==x[1]])

This is not a simple problem for a beginner. 对于初学者来说,这不是一个简单的问题。 A more straightforward approach would use functions like sum and zip with a list comprehension like so: 一种更直接的方法是使用诸如sumzip类的函数,并具有如下列表理解功能:

def commons(L1, L2):
    return  sum(el1 == el2 * 1 for el1, el2 in zip(L1, L2))

A more typical but error prone approach taken by beginners is: 初学者采用的更典型但容易出错的方法是:

def commons(L1, L2):
    count = 0
    for i, elem in enumerate(L2):
        if elem == L1[i]:
            count += 1
    return count

I say this is more error prone because there are more parts to get right. 我说这更容易出错,因为有更多部分需要纠正。

Without using enumerate you could do: 不使用enumerate您可以执行以下操作:

def commons(L1, L2):
    count = 0
    for i, range(len(L2)):
        if L1[i] == L2[i]:
            count += 1
    return count

but these previous two will work only if len(L2) <= len(L1) . 但是前两个仅在len(L2) <= len(L1) See what I mean by more error prone? 明白我的意思是更容易出错吗? To fix this you would need to do: 要解决此问题,您需要执行以下操作:

def commons(L1, L2):
    count = 0
    for i, range(min(len(L2), len(L1))):
        if L1[i] == L2[i]:
            count += 1
    return count

Seems like this would work: 似乎这样可以工作:

def commons(l1, l2):
   return sum(1 for v1,v2 in map(None, l1,l2) if v1 == v2)
  • Note: The degenerate form of map used here results in None being returned for all values in the shorter list (so even if l1 and l2 are not the same length, it'll work.) It assumes that both lists all have values (ie, L1 and L2 do not contain None - since that would end up in false positives if one list was shorter than the other.) 注意:此处使用的简并形式的map导致较短列表中的所有值都返回None(因此,即使l1和l2的长度不相同,也可以使用。)假定两个列表都具有值(即,L1和L2不包含“无”-因为如果一个列表比另一个列表短,那将导致误报。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM