合并两个列表(不使用pandas)

4
我正在尝试在Python中使用两个列表执行内连接,而不使用pandas或numpy库。
函数combine具有以下参数: One:第一个列表;Two:第二个列表;left:第一个列表中列的索引;right:第二个列表中列的索引
我正在尝试根据每个列表的索引将它们组合在一起,然后将它们的元素连接在一起。
到目前为止,我的代码是这样的:
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']]

你有任何想法/技巧可以完成这个任务吗?


3
你的索引有误,左侧索引应为1。 - njzk2
2
one: 'apple' != 'fruit''vegetable'。对于 two,类似。尝试使用 combine(one, two, 1, 0),但您需要将 combined = [x,y] 更改为 combined.append(x + y) - aydow
2个回答

1
在我看来,你应该这样调用函数:
combine(one, two, 1, 0 )

由于位置 one[1] 与 two[0] 具有相同的值。


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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接