【问题标题】:Python format and print data in specific order from nested ListPython 格式化并按嵌套列表中的特定顺序打印数据
【发布时间】:2021-02-15 21:25:49
【问题描述】:

我有一个如下所示的列表:

[(6, {3: 3, 4: 3, 7: 2, 1: 3, 11: 2}), 
(1, {7: 3, 9: 2, 11: 4, 3: 2, 6: 3, 4: 3, 12: 2}), 
(4, {3: 2, 7: 3, 6: 3, 1: 3, 11: 2, 12: 3}), (2, {9: 4, 8: 2, 10: 2, 5: 2})

我需要将其格式化并打印出来,如下所示:

 6:Might(1,3,4,7,11) 
 1:Might(4,6,7) Probably(11)
 4:Might(1,3,6,11,12) 
13:

我试过这个:

for item in connect_out:
name = item[0]
pair_dict = item[1]
might = []
probably = []
for key, value in pair_dict.items():
    if value > 3:
        probably.append(str(value))
    else:
        might.append(str(value))
might = sorted(might)
probably = sorted(probably)
print("%s:Might(%s) Probably(%s)" % (name, ','.join(might),','(probably)) )

我得到了这个:

    6:Might(2,2,3,3,3) Probably()
    1:Might(2,2,2,3,3,3) Probably(4)
    4:Might(2,2,3,3,3,3) Probably()
   13:Might() Probably()

如果可能或可能列表中没有任何内容,则不应打印任何标题。我在里面放了一些打印语句,看起来它是把冒号后面的数字放在可能列表中,而不是放在它前面的那个。

【问题讨论】:

  • 如果您展示您已经尝试过的内容以及出了什么问题,也许会更清楚问题所在。
  • 在 SO 上,您必须尝试自己编写代码并发布您尝试过的代码并解释它的问题所在。
  • 您正在尝试处理 json。那是一个元组列表,其中元组中的第二个元素是一个字典。请查看关于 SO 的所有现有问题和答案。

标签: python list


【解决方案1】:

在将其发送到print() 之前,您需要进行一些预处理 你可以这样开始:

values = [(6, {3: 3, 4: 3, 7: 2, 1: 3, 11: 2}), 
(1, {7: 3, 9: 2, 11: 4, 3: 2, 6: 3, 4: 3, 12: 2}), 
(4, {3: 2, 7: 3, 6: 3, 1: 3, 11: 2, 12: 3}), (2, {9: 4, 8: 2, 10: 2, 5: 2})]
for item in values:
    name = item[0]
    pair_dict = item[1]
    might = []
    probably = []
    for key, value in pair_dict.items():
        if value > 3:
            probably.append(value)
        else:
            might.append(value)
    might = sorted(might)
    probably = sorted(probably)
    print("%s:Might(%s) Probably(%s)" % (name, ','.join(might), ','.join(probably))

编辑:在稍微修改并更好地理解您的要求后,试试这个尺寸:

values = [(6, {3: 3, 4: 3, 7: 2, 1: 3, 11: 2}), 
(1, {7: 3, 9: 2, 11: 4, 3: 2, 6: 3, 4: 3, 12: 2}), 
(4, {3: 2, 7: 3, 6: 3, 1: 3, 11: 2, 12: 3}), (2, {9: 4, 8: 2, 10: 2, 5: 2})]
for item in values:
    name = item[0]
    pair_dict = item[1]
    might = []
    probably = []
    for key, value in pair_dict.items():
        if value > 3:
            probably.append(value)
        else:
            might.append(value)
    might = [str(i) for i in sorted(might)]
    probably = [str(i) for i in sorted(probably)]
    mightstr = "" if len(might) == 0 else "Might(%s) " % ','.join(might)
    probablystr = "" if len(probably) == 0 else "Probably(%s)" %  ','.join(probably)
    print("%s:%s%s" % (name, mightstr, probablystr))

【讨论】:

  • 它把错误序列项0:预期字符串,找到了我,所以我在追加时将值转换为str,但输出不正确。我得到了这个 6:可能(2,2,3,3,3)可能() 1:可能(2,2,2,3,3,3)可能(4)
  • 当没有任何东西时,它也会打印可能和可能 - 像这样 10:Might(2,2,2,3,3) Possible() 和这个 13:Might() Possible() s /b 10:Might(#,#,#) 如果没有可能,则后面没有任何内容,而 13 应该只是这个 13: 没有可能或可能带有空括号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-24
  • 1970-01-01
  • 2012-11-26
相关资源
最近更新 更多