<p>编辑:以上来自@Austin和@Mad Physician的解决方案更好,所以最好使用它们。我的工作是重新发明自行车,这不是Python式的方式</p>
<p>我认为修改原始数组是危险的,尽管这种方法使用了两倍的内存,但以这种方式进行迭代和操作是安全的。
发生了什么:</p>
<ol>
<li>在<code>a</code>上迭代,并在a(我们
通过<code>remove(i)</code>排除当前值</li>
<li>如果没有重复项,就照常复制<code>b</code>和<code>c</code></li>
<li>如果有,则在临时列表中合并,然后将其附加到<code>a1</code>,<code>b1</code>
和<code>c1</code>。阻塞值,这样重复的值就不会触发另一个
合并。在开始时使用if可以检查值是否被阻止</li>
<li>返回新列表
虽然我使用了<code>np.where</code>,但我没有使用np数组,因为它比使用列表理解快一点。请随意编辑数据格式等,我的数据格式非常简单,便于演示</li>
</ol>
<pre><code>import numpy as np
a = [1.0, 1.5, 1.5, 2, 2]
b = [[1, 2, 3, 4, 10], [4, 8, 10, 11, 5, 6, 12], [1, 5, 7], [70, 1, 2], [1]]
c = [[3, 4, 8], [5, 6, 12], [6, 7, 10, 123, 14], [70, 1, 2], [1, 5, 10, 4]]
def function(list1, list2, list3):
a1 = []
b1 = []
c1 = []
merged_list = []
# to preserve original index we use enumerate
for i, item in enumerate(list1):
# to aboid merging twice we just exclude values from a we already checked
if item not in merged_list:
list_without_elem = np.array(list1)
ixs = np.where(list_without_elem == item)[0].tolist() # removing our original index
ixs.remove(i)
# if empty append to new list as usual since we don't need merge
if not ixs:
a1.append(item)
b1.append(list2[i])
c1.append(list3[i])
merged_list.append(item)
else:
temp1 = [*list2[i]] # temp b and c prefilled with first b and c
temp2 = [*list3[i]]
for ix in ixs:
[temp1.append(item) for item in list2[ix]]
[temp2.append(item) for item in list3[ix]]
a1.append(item)
b1.append(temp1)
c1.append(temp2)
merged_list.append(item)
print(a1)
print(b1)
print(c1)
</code></pre>
<pre><code># example output
# [1.0, 1.5, 2]
# [[1, 2, 3, 4, 10], [4, 8, 10, 11, 5, 6, 12, 1, 5, 7], [70, 1, 2, 1]]
# [[3, 4, 8], [5, 6, 12, 6, 7, 10, 123, 14], [70, 1, 2, 1, 5, 10, 4]]
</code></pre>