0

私は以下を持っており、Pythonの実装に関するいくつかのガイダンスが必要です..アルゴリズムと予想される出力を明確に文書化しました..入力は本当に感謝しています..

data_changes ={'305403': ['302180'], '312994': ['311957'], '311957': ['312621'] }
modem_changes = {'305403': [], '313113': [], '312994': ['253036', '312591'], '311957': []}

for keys that are present in both data_changes and modem_changes:
        write data to a file "file.txt" in the order key-->data_changes_values-->modem_changes_values

for keys that exist in only one of data_changes and modem_changes :
        append data to the same file "file.txt" key--> data_changes_values or key-->modem_changes values

EXPECTED OUTPUT:-

Create a text file with the following data

305403 302180
312994 311957 253036 312591
311957 312621
313113

以下は私が試したものですが、私の目的を果たしていません...

build_dep_list= [i
for k, v in itertools.chain.from_iterable(d.iteritems() for d in (data_changes, modem_changes))
for i in [k] + (v or [])
if i]
print "BUILD LIST"
print list(set(build_dep_list))

CURRENT OUTPUT:-
['305403', '302180', '313113', '311957', '312621', '253036', '312994', '312591']
4

2 に答える 2

1

sを使用するsetと、交差と対称差の難しい作業が効率的に行われます。

data_changes = {'305403': ['302180'], '312994': ['311957'], '311957': ['312621'] }
modem_changes = {'305403': [], '313113': [], '312994': ['253036', '312591'], '311957': []} 

dc_set = set(data_changes)
mc_set = set(modem_changes)

# open a file in append mode    
fh = open('myfile.txt', 'a')

for key in dc_set.intersection(mc_set):
    union_values = data_changes[key] + modem_changes[key]
    fh.write('%s,%s\n' % (key, ','.join(union_values)))

for key in dc_set.symmetric_difference(mc_set):
    dc_values = data_changes.get(key) or []
    mc_values = data_changes.get(key) or []
    union_values = dc_values + mc_values
    fh.write('%s,%s\n' % (key, ','.join(union_values)))

fh.close()

http://docs.python.org/2/library/sets.html

キーは両方の辞書にあるため、最初のものはかなり簡単です。それ以外の場合、キーがどのディクショナリに存在するかわかりません。このgetメソッドは、指定されたキーの値を取得しようとし、None見つからない場合は戻ります。or見つからない場合は、ステートメントからの空のリストがデフォルトになります。

于 2013-05-02T03:43:05.197 に答える