【问题标题】:Python match elements of jth row of list with other rowsPython将列表第j行的元素与其他行匹配
【发布时间】:2017-02-07 07:58:55
【问题描述】:

我有一个列表列表,我想在其中比较特定列的所有元素以查找匹配项。更具体地说,我有下表:

Item_No.      features
   A        ['X','Y','Z']
   B          ['X','Y']
   C            ['Y']
   D            ['S']

我想看看物品A是否与其他物品有任何共同特征。在这种情况下,我想获得这样的东西:

Item_No.    features      Common
   A      ['X','Y','Z']    B,C
   B        ['X','Y']       A,C
   C          ['Y']         A,B
   D          ['S']         0

我将如何在 python 上进行此操作?

【问题讨论】:

  • 你是不是先自己尝试了一些东西?
  • 为什么B,C在common中什么都没有?您应该更正示例或指定commonOT:添加到问题中的标签看起来有点牵强。
  • @nitzel - 已编辑。
  • Kedar Kodgire 已经说过,如果您向我们展示您的尝试,我们愿意帮助您。从another post of yours 我知道你知道for inin。这是您完成任务的良好开端。

标签: python anaconda


【解决方案1】:
def common(x,y):
    """Do list x and y have an element in common?"""
    for e in x:
        if e in y:
            return True
    return False

#listnames and their content
data = [('A',['X','Y','Z']),
        ('B',['X','Y']),
        ('C',['Y']),
        ('D',['S'])]

# touples of listnames and an array of listnames it 
data_common = [] overlaps with
# try common on each pair of lists saving their names.
for N,A in d:
    data_common.append((N,[n for n,a in data if(n is not N and common(A,a))]))
print(data_common)

输出:[('A', ['B', 'C']), ('B', ['A', 'C']), ('C', ['A', 'B']), ('D', [])]

这个挺贵的,大概O(m^2*n^2)m=max(len(data[,1])), n=len(data) 并且当然可以进行优化,因为每个列表都经过实际检查 互相两次。

【讨论】:

  • 抱歉,我发布问题后有点忙,无法发布我的工作代码。非常感谢@nitzel。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 2023-02-12
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
相关资源
最近更新 更多