将字典格式化为具有可变数值的字符串

时间:2016-03-06 05:04:04

标签: python dictionary

给出一本字典

@IBAction func startButton2(sender: AnyObject) {
    paintCell2(0)
}

func paintCell2(index: Int) {
    let indexPath = NSIndexPath(forItem: index, inSection: 0)
    let cell = self.collectionView.cellForItemAtIndexPath(indexPath)
    cell?.contentView.backgroundColor = UIColor.blackColor()

    if index < 25 {
        let delay = Int64(NSEC_PER_SEC)
        let time = dispatch_time(DISPATCH_TIME_NOW, delay)
        dispatch_after(time, dispatch_get_main_queue()) {
            self.paintCell2(index + 1)
        }
    }
}

我想要一个打印出来的功能:

  x = {'b': {d}, 'a': {'b', 'c'}, 'd': {'g'}, 'f': {'d', 'g'}, 'c': {'e', 'f'}, 'e': {d}}

我写了这个:

  a -> ['b', 'c']
  b -> ['d']
  c -> ['e', 'f']
  d -> ['g']
  e -> ['d']
  f -> ['d', 'g']

它有效,但很糟糕。我怎样才能做得更好?

4 个答案:

答案 0 :(得分:0)

假设你的意思是:

x = {'b': {'d'}, 'a': {'b', 'c'}, 'd': {'g'}, 'f': {'d', 'g'}, 'c': {'e', 'f'}, 'e': {'d'}}

(与键'b'和'e'关联的值在引号中,与键'a'关联的值为{'b','c'},而不是{'c','d'} )

然后这将给出您列出的输出:

for k in sorted(x.keys()):
    print("{} -> {}".format(k, sorted(list(x[k]))))

答案 1 :(得分:0)

x = {'b': {'d'}, 'a': {'c', 'd'}, 'd': {'g'}, 'f': {'d', 'g'}, 'c': {'e', 'f'}, 'e': {'d'}}


def graph_as_str(x):
    sorted_x = sorted(x)

    for i in x:
        print i, "-->", list(x[i])

希望这能解决您的需求,并且更加简单。享受!!!!

答案 2 :(得分:0)

假设d也被引用:

x = {'b': {'d'}, 'a': {'c', 'b'}, 'd': {'g'}, 'f': {'d', 'g'}, 
    'c': {'e', 'f'}, 'e': {'d'}}

x_str = '\n'.join([key + ' -> ' + str(sorted(list(val))) 
                   for key, val in sorted(x.iteritems())])
print(x_str)    

答案 3 :(得分:0)

OP确实请求了一个函数,并给出了一个精确的格式:

x = {'b': {'d'}, 'a': {'c', 'b'}, 'd': {'g'}, 'f': {'d', 'g'}, 'c': {'e', 'f'}, 'e': {'d'}}

def graph_as_str(graph: {str:{str}}) -> str:
    return "\n".join("  {} -> {}".format(key, sorted(value)) for key, value in sorted(graph.items()))