0

私はこのような辞書を持っています:

d = {'Date' : ['2013-05-01', '2013-05-01', '2013-05-01', '2013-05-01'],
     'Country Code' : ['93', '92', '91', '90'],
     'Area Code' : ['1,2,3,4,5,6,7', '31,32,43,44,54,56,7, ', '434,34,4', '00, 89']}

私はこのような辞書が欲しいです:

d = {'Date' : ['2013-05-01', '2013-05-01', '2013-05-01', '2013-05-01'],
     'Combined Code' : ['931,932,933,934,935,936,937', '9231,9232,9243,9244,9254,9256,927,92 ,', '91434,9134,914', '9000, 9089']}

私が試したことは:

list(chain(*(product(*(s.split(",") for s in e)) for e in zip(*d.values()))))

しかし、これをすべて辞書で管理することはできません。

4

2 に答える 2

2

これは少し野蛮な力かもしれませんが、ちょっと...遅いです。

d = {'Date': ['2013-05-01', '2013-05-01', '2013-05-01', '2013-05-01'], 'Country Code': ['93', '92', '91', '90'], 'Area Code': ['1,2,3,4,5,6,7', '31,32,43,44,54,56,7, ', '434,34,4', '00, 89']}

new = {'Date': d['Date'], 'Combined Code': []}

for i, code in enumerate(d['Country Code']):
    area = map(str.strip, d['Area Code'][i].split(','))
    new['Combined Code'].append(",".join(["".join(item) for item in zip([code] * len(area), area)]))

print new

出力

{'Date': ['2013-05-01', '2013-05-01', '2013-05-01', '2013-05-01'], 'Combined Code': ['931,932,933,934,935,936,937', '9231,9232,9243,9244,9254,9256,927,92', '91434,9134,914', '9000,9089']}
于 2013-03-14T07:51:17.413 に答える
1

私はこれを思いついた。目的の出力の違いは、入力のスペースによるものです。

d = {'Date' : ['2013-05-01', '2013-05-01', '2013-05-01', '2013-05-01'],
     'Country Code' : ['93', '92', '91', '90'],
     'Area Code' : ['1,2,3,4,5,6,7', '31,32,43,44,54,56,7, ', '434,34,4', '00, 89']};

merged = [];

# assumes that the length of "Country Code" is always the same as "Area Code"
for index in range(0, len(d["Area Code"])):
    merged.append(",".join(map(lambda x: d["Country Code"][index] + x.strip(), d["Area Code"][index].split(","))));

# add the result to the dictionary and remove the old entries
d["Combined Code"] = merged;
del d["Country Code"];
del d["Area Code"];

print d;
于 2013-03-14T07:51:46.163 に答える