<p><strong>&barciewicz</strong>根据您提供的输入和预期的输出,我也尝试用我的方式解决这个问题。你知道吗</p>
<blockquote>
<p><strong>Note»</strong> I have used <strong>OrderedDict()</strong> from <strong>collections</strong> module to retain the order of keys in dictionary. I've also used <strong>json</strong> module to pretty print the dictionaries, list etc.</p>
</blockquote>
<p>我展示了3种不同的方法来获得3个独立函数的结果,如下所示。你知道吗</p>
<blockquote>
<p>{
"group1": "1a,2b,3c,4d,7f",
"group2": "5a,8c,6d",
"group3": "10a,9c"
}</p>
</blockquote>
<p>你知道吗</p>
<blockquote>
<p>{
"group1": {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"f": 7
},
"group2": {
"a": 5,
"c": 8,
"d": 6
},
"group3": {
"a": 10,
"c": 9
}
}</p>
</blockquote>
<p>你知道吗</p>
<blockquote>
<p>{
"a": [
1,
5,
10
],
"b": [
2
],
"c": [
3,
8,
9
],
"d": [
4,
6
],
"f": [
7
]
}</p>
</blockquote>
<p>你知道吗</p>
<p>»在<a href="http://rextester.com/OYFF74927" rel="nofollow noreferrer">http://rextester.com/OYFF74927</a>上在线尝试下面的代码。你知道吗</p>
<pre><code>from collections import OrderedDict
import json;
def get_formatted_transactions(parents, partials):
d = OrderedDict();
for index, partial in enumerate(partials):
if parents[index] in d:
l = d[parents[index]]
l.append(partial)
d[parents[index]] = l;
else:
d[parents[index]] = [partial]
return d;
def get_groups(transactions):
i = 1;
groups = OrderedDict();
while transactions:
group_name = "group" + str(i);
groups[group_name] = {};
keys = list(transactions.keys());
for key in keys:
if transactions[key]:
groups[group_name][key] = transactions[key].pop(0);
if not transactions[key]:
del transactions[key];
else:
del transactions[key]
i += 1;
return groups;
def get_comma_separated_data(groups):
new_dict = OrderedDict();
for group_name in groups:
d = groups[group_name]
new_dict[group_name] = ",".join([str(value) + key for value, key in zip(d.values(), d.keys())])
return new_dict;
# Starting point
if __name__ == "__main__":
partials = [1,2,3,4,5,6,7,8,9,10];
parents = ['a','b','c','d','a','d','f','c','c','a'];
transactions = get_formatted_transactions(parents, partials);
# Pretty pritining ordered dictionary
print(json.dumps(transactions, indent=4));
print("\n");
# Creating groups to organize transactions
groups = get_groups(transactions)
# Pretty printing
print(json.dumps(groups, indent=4))
print("\n");
# Get comma separated form
comma_separated_data = get_comma_separated_data(groups);
# Pretty printing
print(json.dumps(comma_separated_data, indent=4));
</code></pre>
输出»
<pre><code>{
"a": [
1,
5,
10
],
"b": [
2
],
"c": [
3,
8,
9
],
"d": [
4,
6
],
"f": [
7
]
}
{
"group1": {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"f": 7
},
"group2": {
"a": 5,
"c": 8,
"d": 6
},
"group3": {
"a": 10,
"c": 9
}
}
{
"group1": "1a,2b,3c,4d,7f",
"group2": "5a,8c,6d",
"group3": "10a,9c"
}
</code></pre>