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

使用sets...他们将有效地完成交叉点和对称差异的艰苦工作:

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 回答
0

for 循环可以写成:

with open('file.txt', 'r') as f:
    dc_keys = data_changes.keys()
    mc_keys = modem_changes.keys()

    for key in dc_keys:
        if key not in modem_changes.keys(): continue
        f.write('key-->' + ','.join(data_changes[key]) + '-->' + ','.join(modem_changes[key]) + '\n')

    for key in mc_keys:    
        if key in dc_keys: continue
        f.write('key-->' + ','.join(modem_changes[key]))

    for key in dc_keys:    
        if key in mc_keys: continue
        f.write('key-->' + ','.join(data_changes[key]))      

我已将答案更新为仅使用列表,因为这更适合您的需求。至于文件写入,我已经对其进行了更新,以便它实际写入文件。

于 2013-05-02T03:04:52.127 回答