我正在尝试在Python中使用两个列表执行内连接,而不使用pandas或numpy库。
函数combine具有以下参数: One:第一个列表;Two:第二个列表;left:第一个列表中列的索引;right:第二个列表中列的索引
我正在尝试根据每个列表的索引将它们组合在一起,然后将它们的元素连接在一起。
到目前为止,我的代码是这样的:
函数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']]
你有任何想法/技巧可以完成这个任务吗?
one
:'apple' != 'fruit'
或'vegetable'
。对于two
,类似。尝试使用combine(one, two, 1, 0)
,但您需要将combined = [x,y]
更改为combined.append(x + y)
。 - aydow