合并2个列表(不使用熊猫)

时间:2018-11-19 02:45:43

标签: python python-2.7

我正在尝试使用python中的2个列表进行内部联接,而不使用pandas或numpy库。

功能合并具有参数: 一个:第一名单;二:第二名单;左:第一个列表中列的索引;右:第二个列表中列的索引

我正在尝试基于每个列表的索引合并两个列表,这些索引的元素相等,然后将它们的元素连接在一起。

到目前为止,我有以下代码:

def combine(one, two, left, right):
    combined = []
    for x in one:                         #for elements in list one
        for y in two:                     #for elements in list two
            if x[left] == y[right]:       #if both elements at each indice equal
                combined = [x,y]          #place x and y values into combined list

    print(combined)


one = [['apple', 'fruit'],
       ['broccoli', 'vegetable']]
two = [['fruit', '1'],
       ['vegetable', '1']]

combine(one, two, 1, 0 )

由于某种原因,我得到了一个空列表:[]

所需的输出是:

 [['apple', 'fruit', 'fruit', '1'],
 ['broccoli', 'vegetable', 'vegetable', '1']]

我如何实现此目标的任何想法/提示?

2 个答案:

答案 0 :(得分:1)

从我的角度来看,您应该像这样调用函数:

combine(one, two, 1, 0 )

由于位置one [1]是与2 [0]具有共同值的位置。

答案 1 :(得分:1)

我希望这段代码对您有所帮助!

def combine(one, two, left, right):
    combined = []
    for x in one:  #for elements in list one
        for y in two:  #for elements in list two
            if x[left] == y[right]:  #if both elements at each indice equal
                combined.append(
                    x + y)  #place x and y values into combined list

    print(combined)


one = [['apple', 'fruit'], ['broccoli', 'vegetable']]
two = [['fruit', '1'], ['vegetable', '1']]

combine(one, two, 1, 0)
相关问题