擅长:python、mysql、java
<p>您可以这样做,假设每个子数组的每个位置都有一个以上的非<code>None</code>值(如示例数据所示):</p>
<pre><code>import collections
from pprint import pprint
mainArray = [['dog', None, None, 'bark', None],
['dog', 'brown', None, None, None],
['dog', None, 'happy', None, None],
['cat', 'black', None, None, None],
['cat', None, None, 'soft', None],
['cat', None, None, None, 'purr']]
temp_dict = collections.OrderedDict()
for row in mainArray:
key = row[0]
if key not in temp_dict:
temp_dict[key] = [row[1:]]
else:
temp_dict[key].append(row[1:])
mainArray = []
for key,rows in temp_dict.items():
merged = [None] * len(rows[0])
for row in rows:
for i in range(len(row)):
if row[i] is not None:
merged[i] = row[i]
mainArray.append([key] + merged)
pprint(mainArray)
</code></pre>
<p>输出(这是正确的,尽管与您显示的略有不同):</p>
<pre class="lang-none prettyprint-override"><code>[['dog', 'brown', 'happy', 'bark', None],
['cat', 'black', None, 'soft', 'purr']]
</code></pre>