我在Python中有一本字典,看起来像这样
{123: [u'6722000', u'6722001', u'6631999', u'PX522.X522.091003143054.S4J2', u'PXX22.XX22.140311131347.A6D4', u'7767815060', u'6631900', u'7767815062', u'18001029945', u'7767815063'],...}
当我想打印字典的值(或将其存储在txt文件中)时,我只想要具有" P"的值。在它而不是只有数字的那个。
例如,上面的字典应该看起来像
{123: [u'PX522.X522.091003143054.S4J2', u'PXX22.XX22.140311131347.A6D4'],...}
这是我写的代码
components = nx.connected_component_subgraphs(G)
for idx, comp in enumerate(components):
if "P" in comp.nodes():
comp_dict.update({idx: comp.nodes()})
但它没有给我输出。 如果我在没有if语句的情况下执行代码,我将获得具有所有值的相同输出。
答案 0 :(得分:0)
enumerate将为您提供迭代器索引和iterable的值。在这种情况下,键的键和索引。不是键的值。因为值是一个字符串列表,你必须检查" P"在列表中的字符串中。试试这样:
for idx, comp in components.items():
for s in comp:
if "P" in s:
print(s)
答案 1 :(得分:0)
内嵌评论的代码:
a_dict = {123: [u'6722000', u'6722001', u'6631999', u'PX522.X522.091003143054.S4J2', u'PXX22.XX22.140311131347.A6D4', u'7767815060', u'6631900', u'7767815062', u'18001029945', u'7767815063'],
456: [u'6722000', u'6722001', u'6631999', u'PX522.X522.091003143054.S4J2']}
print "Before...",a_dict
#Iterate over keys of dictonary
for k in a_dict.keys():
#Check the values in list for 'P'. Keep only which has 'P'
tmp_list = [i for i in a_dict[k] if "P" in i]
#Update dictionary with new list
a_dict[k]=tmp_list
tmp_list = []
print "After...", a_dict
<强>输出:强>
C:\Users\dinesh_pundkar\Desktop>python c.py
Before... {456: [u'6722000', u'6722001', u'6631999', u'PX522.X522.091003143054.S
4J2'], 123: [u'6722000', u'6722001', u'6631999', u'PX522.X522.091003143054.S4J2'
, u'PXX22.XX22.140311131347.A6D4', u'7767815060', u'6631900', u'7767815062', u'1
8001029945', u'7767815063']}
After... {456: [u'PX522.X522.091003143054.S4J2'], 123: [u'PX522.X522.09100314305
4.S4J2', u'PXX22.XX22.140311131347.A6D4']}
C:\Users\dinesh_pundkar\Desktop>
如果您有疑问,请告诉我。